(Note: this is for MS SQL Server)
Say you have an ABC table with a primary key identification column and a CODE column. We want each line to have a unique, sequentially generated code (based on some typical check digit formula).
Say you have another DEF table with only one row that stores the next available code (imagine a simple auto-dial number).
I know that logic like the one below represents a race condition in which two users can have the same code:
1) Run a select query to grab next available code from DEF 2) Insert said code into table ABC 3) Increment the value in DEF so it not re-used.
I know that two users can get stuck in step 1) and can end up with the same code in the ABC table.
What is the best way to deal with this situation? I thought I could just turn on “start trance” / “make a transition” around this logic, but I don’t think it worked. I had a stored procedure like this one to check, but I did not escape the race condition when I was running from two different windows in MS:
begin tran declare @x int select @x= nextcode FROM def waitfor delay '00:00:15' update def set nextcode = nextcode + 1 select @x commit tran
Can someone shed some light on this? I thought this transaction would prevent another user from accessing my NextCodeTable until the first transaction completes, but I believe that my understanding of transactions is erroneous.
EDIT: I tried moving the wait after the “update” statement, and I got two different codes ... but I suspected that. I have a waitfor command to simulate a delay, so race status can be easily seen. I think the key issue is a misconception about how transactions work.
sql sql-server transactions
Hythloth
source share