Is there a way to retrieve all the keys of the newly inserted records when using an INSERT INTO ... SELECT FROM query?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
DECLARE @MyVar TABLE ( ID int )
INSERT INTO dbo.TargetTable
OUTPUT INSERTED.ID INTO @MyVar
SELECT * FROM dbo.SourceTable
SELECT * FROM @MyVar
回答2:
Use the OUTPUT clause to capture them (SQL Server 2005 and up).
回答3:
Some databases support the INSERT INTO ... SELECT ... RETURNING ...
syntax. Since you are using TSQL, I believe the syntax for that is:
INSERT INTO table (fields...)
OUTPUT outputfields...
SELECT ...
There's a PDF on the issue: Returning.pdf