Most efficient method to detect column change in MS SQL Server

后端 未结 5 1727
情深已故
情深已故 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条回答
  •  Happy的楠姐
    2020-12-05 05:32

    Let's start with I would never and I mean never invoke a stored proc in a trigger. To account for a multi row insert you would have to cursor through the proc. This means the 200,000 rows you just loaded though a set-based query (say upddating all prices by 10%) might well lock the table for hours as the trigger tries valiantly to handle the load. Plus if something changes in the proc, you could break any inserts to the table at all or even completely hang up the table. I'm a firm beliver that trigger code should call nothing else outside the trigger.

    Personally I prefer to simply do my task. If I have written the actions I want to do properly in the trigger it will only update, delete or insert where columns have changed.

    Example: suppose you want to update the last_name field that you are storing in two places due to a denormalization placed there for performance reasons.

    update t
    set lname = i.lname
    from table2 t 
    join inserted i on t.fkfield = i.pkfield
    where t.lname <>i.lname
    

    As you can see it would only update the lnames that are different than what is currently in the table I am updating.

    If you want to do auditing and record only those rows which changed then do the comparison using all fields something like where i.field1 <> d.field1 or i.field2 <> d.field3 (etc through all the fields)

提交回复
热议问题