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

后端 未结 2 1432
执念已碎
执念已碎 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: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

提交回复
热议问题