我可以在下面的存储过程中拥有2个事务吗?如果我回滚TRAN1,它是否回滚所有TRAN2?我迷失在这里,任何反馈都会有所帮助。提前致谢
BEGIN TRANSACTION TRAN1
WHILE(...)
BEGIN
BEGIN TRANSACTION TRAN2
BEGIN TRY
.....
.....
.....
COMMIT TRANSACTION TRAN2
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION TRAN2
END CATCH
END
COMMIT TRANSACTION TRAN1
答案 0 :(得分:3)
无论你有多少交易,外部回滚都会回滚所有交易..
当您在事务中嵌套事务时,每个committ / rollback都会增加或减少@@ trancount ..
来自MSDN ..
每个BEGIN TRANSACTION语句将@@ TRANCOUNT递增1。每个COMMIT TRANSACTION或COMMIT WORK语句将@@ TRANCOUNT减一。
ROLLBACK TRANSACTION使用一组嵌套事务中最外层事务的事务名称回滚所有嵌套事务,并将@@ TRANCOUNT减少为0
也可以看到这一点:A SQL Server DBA myth a day: (26/30) nested transactions are real
以下是测试此行为的演示..
if object_id('t1','u') is not null
drop table t1
create table t1
(
id int
)
go
begin tran outertran
select @@trancount--1
insert into t1
select 1
begin tran innertran
select @@trancount--2
insert into t1
select 2
/**below throws error,since you can reference only outer transaction
-referrring inner tran is not legal
***/
--rollback tran innertran
/***
error you get by uncommneting above
Msg 6401, Level 16, State 1, Line 20
Cannot roll back innertran. No transaction or savepoint of that name was found.
**/
commit tran innertran
select @@trancount--1
rollback --rollbacks all
select * from t1
参考文献:
http://www.sqlskills.com/blogs/paul/a-sql-server-dba-myth-a-day-2630-nested-transactions-are-real/