What columns can be used in OUTPUT INTO clause?

前端 未结 5 955
孤街浪徒
孤街浪徒 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:37

    You can do this with a MERGE in Sql Server 2008. Example code below:

    --drop table A
    create table A (a int primary key identity(1, 1))
    insert into A default values
    insert into A default values
    
    delete from A where a>=3
    
    -- insert two values into A and get the new primary keys
    MERGE a USING (SELECT a FROM A) AS B(a)
    ON (1 = 0) -- ignore the values, NOT MATCHED will always be true
    WHEN NOT MATCHED THEN INSERT DEFAULT VALUES -- always insert here for this example
    OUTPUT $action, inserted.*, deleted.*, B.a; -- show the new primary key and source data
    

    Result is

    INSERT, 3, NULL, 1
    INSERT, 4, NULL, 2
    

    i.e. for each row the new primary key (3, 4) and the old one (1, 2). Creating a table called e.g. #OUTPUT and adding " INTO #OUTPUT;" at the end of the OUTPUT clause would save the records.

提交回复
热议问题