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 value from columnA
to be copied to columnB
.
Here's what I have now:
CREATE TRIGGER tUpdateColB
ON products
FOR INSERT, UPDATE AS
BEGIN
UPDATE table
SET columnB = columnA
END
The problem now is that the query affects all rows, not just the one that was updated or inserted. How would I go about fixing that?
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 adeleted
table that will contain the "before" version of rows impacted by an UPDATE or DELETE operation.So, for your specific case:
Assuming you have a primary key column,
id
, (and you should have a primary key), join to theinserted
table (making the trigger capable of handling multiple rows):But if ColumnB is always a copy of ColumnA, why not create a Computed column instead?
Using the inserted and deleted Tables