TSQL ID generation

Posted by Markus on Stack Overflow See other posts from Stack Overflow or by Markus
Published on 2010-05-10T15:27:11Z Indexed on 2010/05/10 15:34 UTC
Read the original article Hit count: 269

Filed under:

Hi. I have a question regarding locking in TSQL. Suppose I have a the following table: A(int id, varchar name), where id is the primary key, but is NOT an identity column.

I want to use the following pseudocode to insert a value into this table:

lock (A)
  uniqueID = GenerateUniqueID()  
  insert into A values (uniqueID, somename)
unlock(A)

How can this be accomplished in terms of TSQL? The computation of the next id should be done with the table A locked in order to avoid other sessions to do the same operation at the same time and get the same id.

© Stack Overflow or respective owner

Related posts about tsql