现在有两个表Table_A 与Table_B,在Table_A表上有Insert触发器,比如:
Create Trigger Trig_Table_A_Insert
on table_a
after insert
as
--做一些操作
insert into Table_B
select * from table_a where id=1说明:table_a与table_b是结构相同的。
问题:在插入table_b前会做一些其它操作,但可以会有错,如果出错,则插入table_a表的也会回滚。
我想实现,如果出错,保证table_a表的插入没有问题。
Create Trigger Trig_Table_A_Insert
on table_a
after insert
as
--做一些操作
insert into Table_B
select * from table_a where id=1说明:table_a与table_b是结构相同的。
问题:在插入table_b前会做一些其它操作,但可以会有错,如果出错,则插入table_a表的也会回滚。
我想实现,如果出错,保证table_a表的插入没有问题。
on table_a
after insert
as
commit tran --> 先提交insert事务
--做一些操作
insert into Table_B
select * from table_a where id=1
begin tran
if exists(select 1 from syscolumns) --模拟错误
begin
rollback tran
raiserror ('afd',16,1)
end
else
insert tb select * from inserted
create table tb(id int)
go
create trigger tri
on ta
for insert
as commit
begin tran
if exists(select 1 from syscolumns) --模拟错误
begin
rollback tran
raiserror ('afd',16,1)
end
else
insert tb select * from inserted
goinsert into ta select 1
/*
服务器: 消息 50000,级别 16,状态 1,过程 tri,行 11
afd*/
select * from ta
/*
id
-----------
1(所影响的行数为 1 行)
*/
select * from tb/*
id
----------- (所影响的行数为 0 行)*/drop table ta,tb