34,588
社区成员
发帖
与我相关
我的任务
分享
create table test2
(id int)
insert into test2 select 1 union all select 2 union all select 3 union all select 999 union all select 999
create trigger trg_999 on test2 instead of delete
as
delete a from test2 a join deleted b on a.id=b.id where b.id<>999
if object_id('[tb]') is not null drop table [tb]
create table [tb]([id] int,[aa] varchar(1))
insert into tb([id],[aa])
select 111,'a' union all
select 222,'a' union all
select 333,'b' union all
select 444,'b' union all
select 777,'c' union all
select 888,'c' union all
select 999,'c'
if (object_id('tgr_classes_delete', 'TR') is not null)
drop trigger tgr_classes_delete
go
create trigger tgr_classes_delete
on tb
for delete --删除触发
as
declare @id int
select @id=[id] from deleted
if(@id=999)
insert into tb([id],[aa])select id,aa from deleted
go
delete tb where id=999
-- 建测试表
create table zh(ID int)
insert into zh(ID)
select 1 union all
select 2 union all
select 999
-- 建触发器
create trigger tr_zh on zh
for delete
as
begin
if exists(select 1 from deleted where ID=999)
begin
rollback tran
end
end
-- 测试1
delete from zh where ID=2
select ID from zh
/*
ID
-----------
1
999
(2 row(s) affected)
*/
-- 测试2
delete from zh where ID=999
/*
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
*/
select ID from zh
/*
ID
-----------
1
999
(2 row(s) affected)
*/
if (object_id('tgr_classes_delete', 'TR') is not null)
drop trigger tgr_classes_delete
go
create trigger tgr_classes_delete
on tb
for delete --删除触发
as
declare @id int
select @id=ID from deleted
if(@id=999)
insert into tb(ID,...)select ID... from deleted
go