如何使用SQL复制行并获取新旧ID?

时间:2012-01-07 23:45:58

标签: sql sql-server

我有一张桌子,我需要复制某些行。我可以获得这样的新行ID:

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

但我想拥有的是这样的:

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

可以使用SQL Server完成吗?

P.S。我不是这样编程的,因为它必须由存储过程完成。

1 个答案:

答案 0 :(得分:7)

通过Andriy M链接到“How to copy tables avoiding cursors in SQL?”的有用链接,我设法提出了这个非常优雅的解决方案:

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;