Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
805 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...