I am trying to write a function that increments and returns an int column value:
CREATE PROCEDURE [GetNextTagSuffix]
AS
BEGIN
UPDATE [MyTable]
SET [NextTagSuffix] = [NextTagSuffix] + 1
OUTPUT DELETED.[NextTagSuffix]
WHERE [MyTableId] = 'SpecialCase'
END
The OUTPUT clause can output INTO a table variable or temp table but I just need that single value so adding it first to a table variable seems silly. Is there any way to assign that value directly to a variable and return it?
RESOLVED using table variable:
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
I believe you have to assign the output to a table variable or temp table. From BOL documentation,
Note how it specified that the output can be selected into a table variable or table.
In 2006 a Microsoft Connect action item was filed requesting exactly the functionality you want to use (the ability to do an assignment to a scalar variable from the results of a OUTPUT clause). Microsoft closed the item as “Closed as Won’t Fix”, so for sure this feature was not available in SQL 2005 and was not put into SQL 2008. So unless they had a change of heart, it is not available in SQL 2012 either. You might want to up-vote the connect item or file a new one requesting this feature in a future SQL release.