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')。 如何爲此編寫代碼?