I have often used something like this. Assume that the MyIDValues
table has only one row, so IDColumn
always holds the most-recently-assigned ID value:
DECLARE @NewID Int
UPDATE MyDB.dbo.MyIDValues SET @NewID = IDColumn = IDColumn + 1
SELECT @NewID
It simultaneously (i.e. as an atomic statement) updates the table to set the incremented value and returns that value.
In my opinion, this is better than taking the current top value because it always avoids collisions (i.e. if you have software that incorrectly does take the top value) by incrementing first and then returning that incremented value.