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

后端 未结 11 1823
刺人心
刺人心 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:28

    I don't know if somebody is still looking for an answer but here is a solution that seems to work:

    -- Preparation: execute only once
        CREATE TABLE Test (Value int)
    
    CREATE TABLE Lock (LockID uniqueidentifier)
    INSERT INTO Lock SELECT NEWID()
    
    -- Real insert
    
        BEGIN TRAN LockTran
    
        -- Lock an object to block simultaneous calls.
        UPDATE  Lock WITH(TABLOCK)
        SET     LockID = LockID
    
        INSERT INTO Test
        SELECT ISNULL(MAX(T.Value), 0) + 1
        FROM Test T
    
        COMMIT TRAN LockTran
    

提交回复
热议问题