Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...