TSQL: UPDATE with INSERT INTO SELECT FROM

前端 未结 7 2406
感情败类
感情败类 2021-02-08 05:11

so I have an old database that I\'m migrating to a new one. The new one has a slightly different but mostly-compatible schema. Additionally, I want to renumber all tables from

7条回答
  •  没有蜡笔的小新
    2021-02-08 06:06

    The best you can do that I know is with the output clause. Assuming you have SQL 2005 or 2008.

    USE AdventureWorks;
    GO
    DECLARE @MyTableVar table( ScrapReasonID smallint,
                               Name varchar(50),
                               ModifiedDate datetime);
    INSERT Production.ScrapReason
        OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
            INTO @MyTableVar
    VALUES (N'Operator error', GETDATE());
    

    It still would require a second pass to update the original table; however, it might help make your logic simpler. Do you need to update the source table? You could just store the new id's in a third cross reference table.

提交回复
热议问题