gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:48:41 24 4
gpt4 key购买 nike

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

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

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

最佳答案

我以前这样做过:

update CounterTable set @Next_Number = Counter = Counter + 1

将其保留在单个语句中,因此(除非您可能切换到“未提交的读取”)不应该对多个调用者产生问题。

关于sql - T-SQL 存储过程从计数器多次获取相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6137624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com