SQL update trigger only when column is modified

后端 未结 5 2116
野趣味
野趣味 2020-12-02 08:19

By looking at other examples I\'ve come up with the following but it doesn\'t seem to work as I would like: I want it to only update the modified information if the Qt

5条回答
  •  甜味超标
    2020-12-02 08:48

    You have two way for your question :

    1- Use Update Command in your Trigger.

    ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
       ON [dbo].[SCHEDULE]
       AFTER UPDATE
    AS BEGIN
        SET NOCOUNT ON;
        IF UPDATE (QtyToRepair) 
        BEGIN
            UPDATE SCHEDULE 
            SET modified = GETDATE()
               , ModifiedUser = SUSER_NAME()
               , ModifiedHost = HOST_NAME()
            FROM SCHEDULE S INNER JOIN Inserted I 
            ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
            WHERE S.QtyToRepair <> I.QtyToRepair
        END 
    END
    

    2- Use Join between Inserted table and deleted table

    ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
       ON [dbo].[SCHEDULE]
       AFTER UPDATE
    AS BEGIN
        SET NOCOUNT ON;    
    
        UPDATE SCHEDULE 
        SET modified = GETDATE()
           , ModifiedUser = SUSER_NAME()
           , ModifiedHost = HOST_NAME()
        FROM SCHEDULE S 
        INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
        INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber                  
        WHERE S.QtyToRepair <> I.QtyToRepair
        AND D.QtyToRepair <> I.QtyToRepair
    END
    

    When you use update command for table SCHEDULE and Set QtyToRepair Column to new value, if new value equal to old value in one or multi row, solution 1 update all updated row in Schedule table but solution 2 update only schedule rows that old value not equal to new value.

提交回复
热议问题