Note that there are some explanatory texts on larger screens.

plurals
  1. POHandling SQL Server concurrency issues
    primarykey
    data
    text
    <p>Sometimes I need to acquire a unique ID and store it with a record, but I am unable to use an identity column. So instead I have a table which provides unique IDs using a label field and an integer. When a unique ID is needed, I call a stored procedure and pass in the label, and it spits out the next ID associated with it. Of course it's important for this to be reliable in an environment with concurrent transactions. That is, the stored procedure should never return the same value twice for a given label. My limited understanding of transaction isolation has led me to do the following:</p> <p>1) Set transaction isolation level to serializable</p> <p>2) SELECT id FROM UniqueIdTable WHERE label = @inputLabel</p> <p>3) UPDATE UniqueIdTable SET id = id + 1 WHERE label = @inputLabel</p> <p>4) Return the id retrieved in 2)</p> <p>But is this actually safe? Isn't it still possible for two threads to concurrently execute up to step 2), even with serializable isolation? It's my understanding that the highest isolation level only guarantees that a single transaction will execute without experiencing phantom rows or changing data from other threads. If this is the case, two simultaneous calls to the GetID function could return the same value.</p> <p>Am I misunderstanding something about the isolation levels? How can I guarantee this won't occur?</p> <hr> <p>I have another problem I need to sort out. Suppose I have a table with a field in it which holds foreign keys for a second table. Initially records in the first table do not have a corresponding record in the second, so I store NULL in that field. Now at some point a user runs an operation which will generate a record in the second table and have the first table link to it. This is always a one-to-one relationship, so if two users simultaneously try to generate the record, a single record is created and linked to, and the other user receives a message saying the record already exists. How do I ensure that duplicates are not created in a concurrent environment?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload