How do I make a trigger that only affects the row that was updated/inserted?

后端 未结 2 1428
执念已碎
执念已碎 2020-12-21 05:05

I have a table with two columns where I need one (columnB) to be a copy of the other one (columnA). So, if a row is inserted or updated, I want the

相关标签:
2条回答
  • 2020-12-21 05:47

    There is a special inserted table available in triggers that will contain the "after" version of rows impacted by an INSERT or UPDATE operation. Similarly, there is a deleted table that will contain the "before" version of rows impacted by an UPDATE or DELETE operation.

    So, for your specific case:

    UPDATE t
        SET t.columnB = t.columnA
        FROM inserted i
            INNER JOIN table t
                ON i.PrimaryKeyColumn = t.PrimaryKeyColumn
    
    0 讨论(0)
  • 2020-12-21 05:56

    Assuming you have a primary key column, id, (and you should have a primary key), join to the inserted table (making the trigger capable of handling multiple rows):

    CREATE TRIGGER tUpdateColB 
    ON products 
    FOR INSERT, UPDATE AS 
        BEGIN 
            UPDATE table 
            SET t.columnB = i.columnA 
            FROM table t INNER JOIN inserted i ON t.id = i.id
        END 
    

    But if ColumnB is always a copy of ColumnA, why not create a Computed column instead?

    Using the inserted and deleted Tables

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