现在有两个表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表的插入没有问题。   

解决方案 »

  1.   

    Create Trigger Trig_Table_A_Insert
    on table_a
    after insert
    as
    commit tran --> 先提交insert事务
       --做一些操作
       insert into Table_B 
       select * from table_a where id=1
      

  2.   

    在触发器里try catch应该是可以的,1楼提过了。
      

  3.   

      commit
      begin tran
      if exists(select 1 from syscolumns) --模拟错误
      begin 
          rollback tran
          raiserror ('afd',16,1)
      end
      else
         insert tb select * from  inserted
      

  4.   

    create table ta(id int)
    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
      

  5.   

    请大家继续讨论触发器只能与被触发语句在一个事务中,如果在触发器中用Commit Transaction 的话,触发器中下面的语句就不执行了。