Cannot use UPDATE with OUTPUT clause when a trigger is on the table

后端 未结 3 1562
生来不讨喜
生来不讨喜 2020-11-29 02:04

I\'m performing an UPDATE with OUTPUT query:

UPDATE BatchReports
SET IsProcessed = 1
OUTPUT inserted.BatchFileXml, inserted.Respons         


        
3条回答
  •  -上瘾入骨i
    2020-11-29 02:24

    To work around this restriction you need to OUTPUT INTO ... something. e.g. declare an intermediary table variable to be the target then SELECT from that.

    DECLARE @T TABLE (
      BatchFileXml    XML,
      ResponseFileXml XML,
      ProcessedDate   DATE,
      RowVersion      BINARY(8) )
    
    UPDATE BatchReports
    SET    IsProcessed = 1
    OUTPUT inserted.BatchFileXml,
           inserted.ResponseFileXml,
           deleted.ProcessedDate,
           inserted.Timestamp
    INTO @T
    WHERE  BatchReports.BatchReportGUID = @someGuid
    
    SELECT *
    FROM   @T 
    

    As cautioned in the other answer if your trigger writes back to the rows modified by the UPDATE statement itself in such a way that it affects the columns that you are OUTPUT-ing then you may not find the results useful but this is only a subset of triggers. The above technique works fine in other cases, such as triggers recording to other tables for audit purposes, or returning inserted identity values even if the original row is written back to in the trigger.

提交回复
热议问题