2014-06-06 33 views
1

我有以下情况。 我有一个插入表的触发器。 当我插入一行时,从这个触发器我想插入一些行到第二个表。 对于这些行中的每一行,我都希望在它自己的事务中执行以防出现问题。 我想在第一个表和所有行(这些有问题的)在第二个原始行。在触发器中回滚嵌套事务

一些代码来重现:

create table test(id int primary key identity(1,1),name nvarchar(10)) 
    create table test2(id int primary key identity(1,1), 
state char(1) check (state in ('a','b'))) 
    go 

    create trigger test_trigger on test for insert 
    as 
    begin 
    declare @char char(1) 

    declare curs cursor for (
    select 'a' 
    union 
    select 'c' 
    union 
    select 'b') 

    open curs 

    fetch next from curs into @char 

    while @@FETCH_STATUS = 0 
    begin 
     begin try 
      begin transaction 
       insert into test2(state) 
       select @char 
      commit 
     end try 
     begin catch 
      print 'catch block' 
      rollback 
     end catch 
    fetch next from curs into @char 
    end 

    close curs 
    deallocate curs 

    end 

    go 

    insert into test(name) values('test') 

    select * from test 
    select * from test2 
    go 

    drop table test 
    drop table test2 

所以从这个片段的样本数据,我想与测试表“测试”,并在TEST2表中的两行(行“A”和'b')。 如何为此编写代码?

回答

1

看起来像最后我得到它的工作。 更正的触发代码:

create trigger test_trigger on test for insert 
    as 
    begin 
    declare @char char(1) 

    set xact_abort off 

    declare curs cursor for (
    select 'a' 
    union 
    select 'c' 
    union 
    select 'b') 

    open curs 

    fetch next from curs into @char 

    while @@FETCH_STATUS = 0 
    begin 
    save transaction t 
     begin try 

       insert into test2(state) 
       select @char 

     end try 
     begin catch 
      print 'catch block' 
      rollback transaction t 
     end catch 
    fetch next from curs into @char 
    end 

    close curs 
    deallocate curs 

    end