Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

sql-server

I have a table in which I need to copy certain rows. I can get IDs of new rows like this:

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

But what I would like to have is 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?

P.S. I'm not doing this programmaticaly, because it has to be done by a stored procedure.

like image 238
gligoran Avatar asked Jan 07 '12 23:01

gligoran


1 Answers

With helpful links from Andriy M's 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;
like image 165
gligoran Avatar answered Nov 16 '22 15:11

gligoran