Most efficient method to detect column change in MS SQL Server

后端 未结 5 1725
情深已故
情深已故 2020-12-05 05:10

Our system runs on SQL Server 2000, and we are in the process of preparing for an upgrade to SQL Server 2008. We have a lot of trigger code where we need to detect a change

5条回答
  •  萌比男神i
    2020-12-05 05:24

    I recommend using the EXCEPT set operator as mentioned by Todd/arghtype above.

    I have added this answer because I put the "inserted" before the "deleted" so that INSERTs will be detected as well as UPDATEs. So I can usually have one trigger to cover both inserts and updates. Can also detect deletes by adding OR (NOT EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted))

    It determines if a value has changed in only the columns specified. I have not investigated its performance compared with the other solutions but it is working well in my database.

    It uses the EXCEPT set operator to return any rows from the left query that are not also found on the right query. This code can be used in INSERT, UPDATE and DELETE triggers.

    The "PKID" column is the primary key. It is required to enable matching between the two sets. If you have multiple columns for the primary key then you will need to include all the columns to do correct matching between the inserted and deleted sets.

    -- Only do trigger logic if specific field values change.
    IF EXISTS(SELECT  PKID
                    ,Column1
                    ,Column7
                    ,Column10
              FROM inserted
              EXCEPT
              SELECT PKID
                    ,Column1
                    ,Column7
                    ,Column10
              FROM deleted )    -- Tests for modifications to fields that we are interested in
    OR (NOT EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted)) -- Have a deletion
    BEGIN
              -- Put code here that does the work in the trigger
    
    END
    

    If you want to use the changed rows in subsequent trigger logic, I usually put the results of the EXCEPT query into a table variable that can be referenced later on.

    I hope this is of interest :-)

提交回复
热议问题