What columns can be used in OUTPUT INTO clause?

前端 未结 5 1012
孤街浪徒
孤街浪徒 2021-02-05 11:45

I\'m trying to build a mapping table to associate the IDs of new rows in a table with those that they\'re copied from. The OUTPUT INTO clause seems perfect for that, but it does

5条回答
  •  耶瑟儿~
    2021-02-05 12:35

    I think I found a solution to this problem, it sadly involves a temporary table, but at least it'll prevent the creation of a dreaded cursor :) What you need to do is add an extra column to the table you're duplicating records from and give it a 'uniqueidentifer' type.

    then declare a temporary table:

    DECLARE @tmptable TABLE (uniqueid uniqueidentifier, original_id int, new_id int)
    

    insert the the data into your temp table like this:

    insert into @tmptable
    (uniqueid,original_id,new_id)
    select NewId(),id,0 from OriginalTable
    

    the go ahead and do the real insert into the original table:

    insert into OriginalTable
    (uniqueid)
    select uniqueid from @tmptable
    

    Now to add the newly created identity values to your temp table:

    update @tmptable
    set new_id = o.id
    from OriginalTable o inner join @tmptable tmp on tmp.uniqueid = o.uniqueid
    

    Now you have a lookup table that holds the new id and original id in one record, for your using pleasure :)

    I hope this helps somebody...

提交回复
热议问题