SQL Server Output Clause into a scalar variable

2019-01-09 02:45发布

问题:

Is there any "simple" way to do this or I need to pass by a table variable with the "OUTPUT ... INTO" syntax?

DECLARE @someInt int

INSERT INTO MyTable2(AIntColumn)
OUTPUT @SomeInt = Inserted.AIntColumn
VALUES(12)

回答1:

You need a table variable and it can be this simple.

declare @ID table (ID int)

insert into MyTable2(ID)
output inserted.ID into @ID
values (1)


回答2:

Over a year later... if what you need is get the auto generated id of a table, you can just

SELECT @ReportOptionId = SCOPE_IDENTITY()

Otherwise, it seems like you are stuck with using a table.