How to use update trigger to update another table?

前端 未结 4 1004
星月不相逢
星月不相逢 2020-12-05 07:01

I am new to triggers and want to create a trigger on an update of a column and update another table with that value.

I have table1 with a year column and if the appl

相关标签:
4条回答
  • 2020-12-05 07:51

    You only need to update the records in table2 if the column intannualyear is involved. Also, this is an alternative UPDATE syntax across two tables from what Martin has shown

    IF UPDATE(intannualyear)
        UPDATE table2
        SET    annualyear = inserted.intannualyear
        FROM   inserted
        WHERE table2.id = inserted.id
    
    0 讨论(0)
  • 2020-12-05 07:57

    To supplement the above answers, if you have to check more than one column you can use a INNER JOIN between inserted and deleted, or several UPDATE() calls:

    IF ( UPDATE(Col1) OR UPDATE(Col2) ) BEGIN ...
    
    0 讨论(0)
  • 2020-12-05 08:02

    You don't reference table1 inside the trigger. Use the inserted pseudo table to get the "after" values. Also remember that an update can affect multiple rows.

    So replace your current update statement with

    UPDATE table2
    SET    table2.annualyear = inserted.intannualyear
    FROM   table2
           JOIN inserted
             ON table2.id = inserted.id  
    
    0 讨论(0)
  • 2020-12-05 08:03

    According to this question, if there's only one "downstream" table then another option with a properly defined foreign key relation would be Cascaded update.

    0 讨论(0)
提交回复
热议问题