I have a table with INT primary key column. I do not want to use GUID or IDENTITY as primary key.
I wanted to know what is the best possible way to get the next ID without using an IDENTITY or GUID as primary key column in the table. I do not mind using GUID or IDENTITY in the table unless it’s the primary key column.
I have to find the next available ID (i.e get the MAX ID and increment it by 1), and use that:
SELECT @id=ISNULL(max(AlbumId)+1,1) FROM Albums
However, I want to prevent other applications from inserting into the table when I’m doing this so that we don’t have any problems.
NOTE: Kindly do not mark this question as DUPLICATE . I have gone through this answer and could not understand it properly. Would anyone be kind enough to explain me what is it they are doing? And can I use the same technique?
For SQL Server 2000 – 2008 R2, using
INT IDENTITYis by far the easiest and most reliable way to do it.Trying to do this yourself is like reinventing the wheel and carries a lot of ways in which it can go wrong – so why bother?? You need to (a) make sure this mechanism is concurrency safe (and just doing
SELECT MAX(ID) + 1is NOT safe!), and you (b) need to make sure your mechanism doesn’t become a major bottleneck in system performance, either…What’s your problem with using
INT IDENTITYas your primary key?? Doesn’t seem very rational…For SQL Server 2012 and newer, you could also consider using a
SEQUENCE(which is basically anIDENTITYthat’s not specifically coupled to a single table)Update: that other SO question that you mention in your post is doing basically a “do-it-yourself” simulation of a
SEQUENCE:sequencename, currentvalue)UPDATEstatement coupled with theOUTPUTclauseWhy so complicated? This is the easiest and most efficient way (other than using an
IDENTITY) to safely handle concurrent requests. TheUPDATEstatement will always exclusively lock that one row in the “sequence table” for the sequence you want to get a newIDfrom – thus preventing any other transactions to grab the sameIDand get duplicated values – and it returns the newIDusing theOUTPUTclause back to the caller.