views:

92

answers:

3

Is there a way to retrieve all the keys of the newly inserted records when using an INSERT INTO ... SELECT FROM query?

+3  A: 

Use the OUTPUT clause to capture them (SQL Server 2005 and up).

Cade Roux
Good to know. I don't have to use cursors anymore :)
ps
A: 

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

Kenaniah
+5  A: 
DECLARE @MyVar TABLE ( ID int )

INSERT  INTO dbo.TargetTable
    OUTPUT  INSERTED.ID INTO @MyVar
SELECT * FROM    dbo.SourceTable

SELECT  * FROM    @MyVar
Damir Sudarevic
Can I have another column that captures the original Id too?
adam0101
I think I got it, I'd just modify the table structure and then change the output line to something like this, right? OUTPUT dbo.SourceTable.ID, INSERTED.ID INTO @MyVar
adam0101
Yes, just add a column to @MyVar and one more INSERTED.Something
Damir Sudarevic