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.
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:
begin lock
if code exists
return code
else
generate code
return code
end lock
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.
So, what would you do to accomplish a "lock" in TSQL?
Thanks a lot.
UPDATE:
I got this error when I try to set the serializable level using this as example:
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
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'.
What does it means?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…