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

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

    If you're doing it in a trigger, you could make sure it's an "INSTEAD OF" trigger and do it in a couple of statements:

    DECLARE @next INT
    SET @next = (SELECT (MAX(id) + 1) FROM Table1)
    
    INSERT INTO Table1
    VALUES (@next, inserted.datablob)
    

    The only thing you'd have to be careful about is concurrency - if two rows are inserted at the same time, they could attempt to use the same value for @next, causing a conflict.

    Does this accomplish what you want?

提交回复
热议问题