请参阅以下代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter PROCEDURE TestProc
AS
BEGIN
begin try
SET NOCOUNT ON;
--SET XACT_ABORT on;
set transaction isolation level read committed
create table #Test (id int)
begin transaction
insert into #Test values (1)
begin transaction
insert into #Test values (2)
commit
select * from #test
commit
select * from #test
end try
begin catch
print 'got here 1'
end catch
END
GO
由此调用:
begin try
exec TestProc
end try
begin catch
print @@TRANCOUNT
end catch
输出结果为:
table 1:
1
2
table 2:
1
2
为什么第一次提交;提交这两笔交易?请看这个链接:http://www.codeproject.com/Articles/4451/SQL-Server-Transactions-and-Error-Handling,其中说:"无论您如何深度嵌套一组事务,只有最后一个COMMIT有效。"。我希望第一个表只包含一行:
table 1
1
答案 0 :(得分:3)
SQL Server将解析这样:
begin transaction
insert into #Test values (1)
begin transaction
insert into #Test values (2)
commit
select * from #test
commit
select * from #test
第一个select *
在第一个交易中。这意味着它可以完全访问先前在该事务中执行的事物。稍后在同一事务中执行的语句可以访问未提交的数据,就像它已经提交一样。