Can I keep old keys linked to new keys when making a copy in SQL?

后端 未结 2 1643
温柔的废话
温柔的废话 2021-01-16 04:55

I am trying to copy a record in a table and change a few values with a stored procedure in SQL Server 2005. This is simple, but I also need to copy relationships in other ta

2条回答
  •  一生所求
    2021-01-16 05:13

    If you need to track both old and new keys in your temp table, you need to cheat and use MERGE:

    Data setup:

    create table T (
        ID int IDENTITY(5,7) not null,
        Col1 varchar(10) not null
    );
    go
    insert into T (Col1) values ('abc'),('def');
    

    And the replacement for your INSERT statement:

    declare @TV table (
        Old_ID int not null,
        New_ID int not null
    );
    merge into T t1
    using (select ID,Col1 from T) t2
    on 1 = 0
    when not matched then insert (Col1) values (t2.Col1)
    output t2.ID,inserted.ID into @TV;
    

    And (actually needs to be in the same batch so that you can access the table variable):

    select * from T;
    select * from @TV;
    

    Produces:

    ID  Col1
    5   abc
    12  def
    19  abc
    26  def
    
    Old_ID  New_ID
    5       19
    12      26
    

    The reason you have to do this is because of an irritating limitation on the OUTPUT clause when used with INSERT - you can only access the inserted table, not any of the tables that might be part of a SELECT.


    Related - More explanation of the MERGE abuse

提交回复
热议问题