T-SQL存储过程从计数器多次获得相同的值

时间:2011-05-26 11:16:47

标签: sql sql-server tsql stored-procedures

我创建了一个存储过程,它应该通过在每次调用时递增表中的值来返回唯一的数字。

ALTER PROCEDURE [dbo].[GetNextNumber] @Next_Number char(9) output AS
BEGIN
    BEGIN TRAN

    DECLARE @Current_Number int
    SET @Current_Number = (SELECT CONVERT(int, Counter) FROM CounterTable)

    IF(@Current_Number IS NULL)
    BEGIN
        SET @Next_Number = '000000000'
        INSERT INTO CounterTable (Counter) VALUES (@Next_Number)
    END
    ELSE IF(@Current_Number >= 999999999)
    BEGIN
         SET @Next_Number = '000000000'
         UPDATE dbo.CounterTable SET Counter = @Next_Number
    END
    ELSE
    BEGIN
        SET @Next_Number = REPLACE(STR(@Current_Number + 1, 9),' ', '0')
        UPDATE dbo.CounterTable SET Counter = @Next_Number
    END

    COMMIT TRAN
END

有时,存储过程会返回两次相同的数字。我做错了什么?

2 个答案:

答案 0 :(得分:3)

我以前做过这个:

update CounterTable set @Next_Number = Counter = Counter + 1

将它保存在单个语句中,所以(除非你切换到Read Uncommitted,可能)不应该有多个调用者的问题。

答案 1 :(得分:2)

您可以使用Table Hints

明确锁定Countertable
...
SET @Current_Number = (
   SELECT CONVERT(int, Counter) 
   FROM CounterTable WITH(Holdlock, Updlock)
)
...