我正在尝试编写一个递增并返回 int 列值的函数:
CREATE PROCEDURE [GetNextTagSuffix]
AS
BEGIN
UPDATE [MyTable]
SET [NextTagSuffix] = [NextTagSuffix] + 1
OUTPUT DELETED.[NextTagSuffix]
WHERE [MyTableId] = 'SpecialCase'
END
OUTPUT子句可以输出INTO表变量或临时表,但我只需要该单个值,因此首先将其添加到表变量中似乎很愚蠢。有没有办法将该值直接分配给变量并返回它?
使用表变量解决:
CREATE PROCEDURE [GetNextTagSuffix]
@TagSuffix int out
AS
BEGIN
DECLARE @tagTable TABLE
(
NextTagSuffix int
)
UPDATE [MyTable]
SET [NextTagSuffix] = [NextTagSuffix] + 1
OUTPUT DELETED.[NextTagSuffix] INTO @tagTable
WHERE [MyTableId] = 'SpecialCase'
SET @TagSuffix = (SELECT MAX(NextTagSuffix) FROM @tagTable)
RETURN @TagSuffix
END