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

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

    We have a similar situation where we needed to increment and could not have gaps in the numbers. (If you use an identity value and a transaction is rolled back, that number will not be inserted and you will have gaps because the identity value does not roll back.)

    We created a separate table for last number used and seeded it with 0.

    Our insert takes a few steps.

    --increment the number Update dbo.NumberTable set number = number + 1

    --find out what the incremented number is select @number = number from dbo.NumberTable

    --use the number insert into dbo.MyTable using the @number

    commit or rollback

    This causes simultaneous transactions to process in a single line as each concurrent transaction will wait because the NumberTable is locked. As soon as the waiting transaction gets the lock, it increments the current value and locks it from others. That current value is the last number used and if a transaction is rolled back, the NumberTable update is also rolled back so there are no gaps.

    Hope that helps.

    Another way to cause single file execution is to use a SQL application lock. We have used that approach for longer running processes like synchronizing data between systems so only one synchronizing process can run at a time.

提交回复
热议问题