April 16, 2009 at 3:37 pm
How can I use a trigger to modify data that is being inserted into a table the trigger references?
SET UP: I need to perform quality assurance on a column in a table by making sure inserted or updated values are the right "class".
SUGGESTED SOLUTION: Use an AFTER trigger to check the class of the inserted or updated column, and change it to the correct value if needed.
PROBLEM: What is the proper syntax to use in the trigger if I need to change the inserted or updated value? Will a simple update statement work?
April 16, 2009 at 3:43 pm
You should use an instead-of trigger; you can simply read the information from the inserted pseudo-table and insert it into your target table with any necessary modifications.
A better way to approach this would be to use a stored proc instead of a trigger, thereby eliminating the trigger overhead - it does rely on all inserts to your target table being done through the proc though, and having the appropriate security in place to enforce that.
April 16, 2009 at 4:23 pm
Thanks, Matt. Have you actually tried using a trigger to change data in the table it references?
April 16, 2009 at 9:00 pm
Here is an example. Your case may be as simple as using a case statement in the select clause or it may involve multiple statements, but ultimately your source will be the inserted table and your destination will be the base table.
create table test (id int, value int);
go
create trigger tr_test on test instead of insert as
begin
insert into test (id, value)
select id, value + 100
from inserted;
end;
go
insert into test (id, value) values (1, 1);
select * from test;
April 17, 2009 at 7:23 am
You can do this in an INSTEAD OF trigger as Matt mentions, but my preference is to use stored procedures for inserts and put this kind of validation in the stored procedure.
Jack Corbett
Consultant - Straight Path Solutions
Check out these links on how to get faster and more accurate answers:
Forum Etiquette: How to post data/code on a forum to get the best help
Need an Answer? Actually, No ... You Need a Question
April 17, 2009 at 12:04 pm
Before you think about triggers,sps, think about using Constraints like Check & all, Get more info from BOL.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply