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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With