I recently got a question on a trigger and I could see that the coder was trying to handle two operations in a single trigger and perform separate actions based on the operation.
Now, we all know that we could create a separate trigger for each operation. However, it is sometimes helpful for maintaining code if we use a single trigger.
Here is a simple example of how to handle the different operations in a single trigger.
create table test(
myfield varchar(1)
)
go
create TRIGGER cstr_test
ON test
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
if exists(select 1 from deleted)
begin
if exists(select 1 from inserted)
begin
print 'update'
end
else
begin
print 'delete'
end
end
else
begin
print 'insert'
end
END
go
insert into test select 1
update test set myfield=2 where myfield=1
delete from test
I hope this helps someone!
David Jedziniak maintains this blog and posts helpful tips and tricks on SQL Server and Dynamics GP development. The opinions expressed here are those of the author and do not represent the views, express or implied, of any past or present employer. The information here is provided without warranty of fitness for any particular purpose.
Subscribe to:
Post Comments (Atom)
SQL 2022 TSQL snapshot backups!
SQL 2022 now actually supports snapshot backups! More specifically, T-SQL snapshot backups. Of course this is hardware-dependent. Here ...
-
If you are reading this, you are probably aware of the fact that you cannot deploy SSRS 2008 reports on an SSRS2005 server. SSRS reports ar...
-
SQL Job to refresh TEST from PRODUCTION Last Updated: 2018.11.12 I like to include each of these steps as a separate job step. If you ...
-
I ran into an issue today where I had a report parameter default that I couldn't seem to get rid of. In BIDS, I deleted the defaults f...
No comments:
Post a Comment