Possible to implement a manual increment with just simple SQL INSERT?

后端 未结 11 2018
刺人心
刺人心 2021-01-05 11:54

I have a primary key that I don\'t want to auto increment (for various reasons) and so I\'m looking for a way to simply increment that field when I INSERT. By simply, I mean

11条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-05 12:12

    Any critiques of this? Works for me.

    DECLARE @m_NewRequestID INT
            , @m_IsError BIT = 1
            , @m_CatchEndless INT = 0
    
    WHILE @m_IsError = 1
        BEGIN TRY
            SELECT  @m_NewRequestID = (SELECT ISNULL(MAX(RequestID), 0) + 1 FROM Requests)
    
            INSERT INTO Requests (  RequestID
                                    , RequestName
                                    , Customer
                                    , Comment
                                    , CreatedFromApplication)
                SELECT  RequestID = @m_NewRequestID
                        , RequestName = dbo.ufGetNextAvailableRequestName(PatternName)
                        , Customer = @Customer
                        , Comment = [Description]
                        , CreatedFromApplication = @CreatedFromApplication
                    FROM    RequestPatterns
                    WHERE   PatternID = @PatternID
    
            SET @m_IsError = 0
        END TRY
        BEGIN CATCH
            SET @m_IsError = 1
            SET @m_CatchEndless = @m_CatchEndless + 1
            IF @m_CatchEndless > 1000
                THROW 51000, '[upCreateRequestFromPattern]: Unable to get new RequestID', 1
        END CATCH
    

提交回复
热议问题