What columns can be used in OUTPUT INTO clause?

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

    I've verified that the problem is that you can only use INSERTED columns. The documentation seems to indicate that you can use from_table_name, but I can't seem to get it to work (The multi-part identifier "m.ContentID" could not be bound.):

    TRUNCATE TABLE main
    
    SELECT *
    FROM incoming
    
    SELECT *
    FROM main
    
    DECLARE @Missing TABLE (ContentID INT PRIMARY KEY)
    INSERT INTO @Missing(ContentID) 
    SELECT incoming.ContentID
    FROM incoming
    LEFT JOIN main
        ON main.ContentID = incoming.ContentID
    WHERE main.ContentID IS NULL
    
    SELECT *
    FROM @Missing
    
    DECLARE @Inserted TABLE (ContentID INT PRIMARY KEY, [Content] varchar(50))
    INSERT INTO main(ContentID, [Content]) 
    OUTPUT INSERTED.ContentID /* incoming doesn't work, m doesn't work */, INSERTED.[Content] INTO @Inserted (ContentID, [Content])
    SELECT incoming.ContentID, incoming.[Content] 
    FROM incoming
    INNER JOIN @Missing AS m
        ON m.ContentID = incoming.ContentID
    
    SELECT *
    FROM @Inserted
    
    SELECT *
    FROM incoming
    
    SELECT *
    FROM main
    

    Apparently the from_table_name prefix is only allowed on DELETE or UPDATE (or MERGE in 2008) - I'm not sure why:

    • from_table_name

    Is a column prefix that specifies a table included in the FROM clause of a DELETE or UPDATE statement that is used to specify the rows to update or delete.

    If the table being modified is also specified in the FROM clause, any reference to columns in that table must be qualified with the INSERTED or DELETED prefix.

提交回复
热议问题