[英]How to add scope_identity() to UNION ALL syntax in SQL Server
我使用UNION ALL
查询多个插入。
如何使用SELECT scope_identity();
对于插入的每一行数据?
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First', 1
UNION ALL
SELECT 'Second', 2
UNION ALL
SELECT 'Third', 3
UNION ALL
SELECT 'Fourth', 4
UNION ALL
SELECT 'Fifth', 5
简短的答案是不,你不能。 SCOPE_IDENTITY仅会给您最后插入的值。 但是您可以使用从2005年开始的OUTPUT子句。 有关如何使用此子句的信息,请参见https://msdn.microsoft.com/zh-cn/library/ms177564.aspx 。
插入多行时,可以使用OUTPUT子句来获取多标识列值,而不是scope_identity()。
Create Table tablename
(id int identity(1,5) Primary KEY, b int , c int)
DECLARE @tempIDs TABLE (id int)
INSERT tablename (b, c)
OUTPUT inserted.id INTO @tempIDs
SELECT 1, 1
UNION ALL
SELECT 2, 2
UNION ALL
SELECT 200, 3
UNION ALL
SELECT 3000, 4
UNION ALL
SELECT 400, 5
Select * from @tempIDs
现在,您的表变量@tempIDs具有使用UNION ALL插入的所有主键数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.