How to copy rows with SQL and get new and old identifiers as a result?

I have a table in which I need to copy specific rows. I can get the new line IDs as follows:

DECLARE @IDs TABLE (ID int)
INSERT T (name, address)
OUTPUT INSERTED.TID INTO @ids
    SELECT name, address
    FROM T

But I would like to have something like this:

DECLARE @IDs TABLE (oldID int, newID int)
INSERT T (name, address)
OUTPUT T.ID, INSERTED.TID INTO @ids
    SELECT name, address
    FROM T

Can this be done with SQL Server?

PS I do not do this programmatically because it must be done using a stored procedure.

+5
source share
1 answer

With useful links from Andriy M, a link to How to copy tables avoiding cursors in SQL? ', I managed to come up with this very elegant solution:

DECLARE @t TABLE (oID int, nID int);

MERGE T s
USING (
        SELECT TID, name, address
        FROM T [s]
      ) d on 0 = 1
WHEN NOT MATCHED
THEN INSERT (name, address)
    VALUES (name, address)
OUTPUT d.TID as oID, Inserted.TID as nID
INTO @t;
+5
source

All Articles