November 21, 2012 at 12:05 am
Hi everyone,
I have a problem that "instead of delete" trigger is not fired from "after insert" trigger. Reading BOL it seems that "after" triggers
should fire "instead of" triggers. I have nested triggers option set to 1, recursive triggers option is on. Below is an example. The example is
very simplified (no constraints, no real life logic) and I use it just to demonstrate the problem. Table t1 has 2 triggers - instead of delete trigger just
writes to t1History table. Second trigger calls delete from t1 if the same row as valid inserted already exists with status 0.
You can see that when test statement1 is called, history row is not created even though the old row is deleted.
Can you please help me understand why the "instead of delete" trigger is not fired from "after" trigger? I have SQL Server 2008 R2.
select SERVERPROPERTY('ProductVersion'), SERVERPROPERTY('ProductLevel'), SERVERPROPERTY('Edition')
10.50.2500.0SP1Enterprise Edition (64-bit)
Thank you,
EKD
create table t1History(
itemCode int,
itemName varchar(200),
eventdate smalldatetime
)
create table t1(
itemCode int,
itemName varchar(200),
itemStatus int --0- old, 1- new
)
insert into t1 (itemCode, itemName, itemStatus) values (1, '111', 0)
insert into t1 (itemCode, itemName, itemStatus) values (1, '222', 1)
go
create trigger t1AfterInsert on t1
for insert
as
delete From t1
where exists (Select 1 from inserted where inserted.itemName = t1.itemName and inserted.itemStatus = 1 and t1.itemStatus = 0)
go
create trigger t1InsteadOfDelete on t1
instead of delete
as
insert into t1History
select itemCode, itemName, GETDATE() from deleted
delete from t1
from t1
join deleted d on d.itemCode = t1.itemCode and d.itemName = t1.itemName and d.itemStatus = t1.itemStatus
go
--test statement1
---- the below statement calls after insert trigger and teh row with status 0 is successfully deleted, but no row in t1History is created!
insert into t1 (itemCode, itemName, itemStatus) values (1, '111', 1)
--test statement2
--the below statement correctly fires instead of delete trigger
delete From t1 where itemName = '222'
March 14, 2013 at 2:17 pm
This thread seems to have gotten to the bottom of the behavior you are seeing:
http://www.sqlservercentral.com/Forums/Topic1430725-391-1.aspx
There are no special teachers of virtue, because virtue is taught by the whole community.
--Plato
March 14, 2013 at 7:38 pm
Thank you for the link!
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy