Note that there are some explanatory texts on larger screens.

plurals
  1. POTSQL mutual exclusive access in a stored procedure
    primarykey
    data
    text
    <p>Several web servers access a SQL Server to get a numeric code, when this code doesn't exist, it has to be autogenerated by the SQL Server.</p> <p>I need to ensure that even if two concurrent calls come in and the code doesn't exist, only one code is created and both calls return the same code. So I have to do something like this:</p> <pre><code>begin lock if code exists return code else generate code return code end lock </code></pre> <p>I've been reading a little about isolation levels and table locking, but I have a terrible mess with all that. First I thought that a SERIALIZABLE isolation level is what I need, but apparently it's not.</p> <p>So, what would you do to accomplish a "lock" in TSQL?</p> <p>Thanks a lot.</p> <p>UPDATE:</p> <p>I got this error when I try to set the serializable level using <a href="http://msdn.microsoft.com/en-us/library/aa213026%28v=sql.80%29.aspx" rel="nofollow">this</a> as example:</p> <pre><code>SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE get_code AS BEGIN SET TRANSACTION ISOLATION LEVEL SERIALIZABLE GO BEGIN TRANSACTION select code from codes where granted is null; END GO </code></pre> <blockquote> <p>Msg 1018, Level 15, State 1, Procedure get_code, Line 4 Incorrect syntax near 'SERIALIZABLE'. If this is intended as a part of a table hint, A WITH keyword and parenthesis are now required. See SQL Server Books Online for proper syntax. Msg 102, Level 15, State 1, Line 5 Incorrect syntax near 'END'.</p> </blockquote> <p>What does it means?</p>
    singulars
    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