给出以下简单测试表:
CREATE TABLE dbo.Test ( Id bigint IDENTITY(1,1) NOT NULL,Name varchar(50) NULL )
我想使用OUTPUT子句在INSERT之后将标识列的值获取为标量变量,但这不起作用:
DECLARE @InsertedId BIGINT; INSERT INTO Test(Name) OUTPUT @InsertedId=inserted.Id VALUES ('Michael') -- Display resulting id for debugging SELECT @InsertedId; -- ...
我知道我可以在INSERT之后使用SCOPE_IDENTITY()轻松地执行此操作,但是可以使用OUTPUT子句作为INSERT语句的一部分而不使用表变量吗?
更新,另一个也是不合法的尝试:
-- Return the id as a result set INSERT INTO Test(Name) OUTPUT inserted.Id AS TheId VALUES ('Michael') -- But you can't use the result set as a derived table... SELECT TheId FROM ( INSERT INTO Test(Name) OUTPUT inserted.Id AS TheId VALUES ('Michael') ) -- ...,or you would be able to do this SELECT TOP 1 @InsertedId=TheId FROM ( INSERT INTO Test(Name) OUTPUT inserted.Id AS TheId VALUES ('Michael') )