我正在尝试编写一个递增并返回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
答案 0 :(得分:2)
我认为你必须将输出分配给表变量或临时表。来自BOL documentation,
<OUTPUT_CLAUSE> ::=
{
[ OUTPUT <dml_select_list> INTO { @table_variable | output_table } [ ( column_list ) ] ]
[ OUTPUT <dml_select_list> ]
}
请注意它如何指定可以将输出选择到表变量或表中。
2006年,Microsoft Connect action item提交了完全要求使用的功能(能够根据OUTPUT子句的结果对标量变量进行赋值)。微软已将该项目关闭为“#34;关闭为未修复&#34;”,因此确保此功能在SQL 2005中不可用,并且未放入SQL 2008.因此,除非他们改变主意,否则在SQL 2012中也不可用。您可能希望在将来的SQL版本中对连接项进行向上投票或提交请求此功能的新项。
答案 1 :(得分:0)
但是你可以在SP中使用输出参数
CREATE PROCEDURE [GetNextTagSuffix]
@value int output
AS
BEGIN
UPDATE [MyTable]
SET [NextTagSuffix] = [NextTagSuffix] + 1
OUTPUT DELETED.[NextTagSuffix]
WHERE [MyTableId] = 'SpecialCase'
END
DECLARE @result int
EXEC GetNextTagSuffix @value=@result output