存储过程中的SQL Server嵌套事务

3

我正在使用SQL Server 2014;我的存储过程将是嵌套事务处理过程,其中它将调用一些具有事务的存储过程。如果内部存储过程中的任何一个出现错误,则会回滚所有操作,例如:

Begin Try
Begin Tran
   Exec Stored Proc 1 (with begin tran inside)
   Exec Stored Proc 2 (with begin tran inside)
   Exec Stored Proc 3 (with begin tran inside)
   Exec Stored Proc 4 (with begin tran inside)
   Exec Stored Proc 5 (with begin tran inside)   
Commit Tran
End Try
Begin Catch
   Catch exception then roll back tran
End Catch

问题是执行内部存储过程后的事务计数不匹配,但如果我在内部存储过程中没有开启事务,则不会回滚。有人可以给我一些建议吗?


在每个过程中使用try catch。在内部过程中回滚事务并向外部过程返回错误。在外部过程中,如果从任何内部过程获取错误,则打破调用每个事务的循环并回滚。 - S3S
嗨@scsimon,谢谢你的建议。 假设存储过程1和2成功执行,但是存储过程3出现错误。那么外层的catch块和回滚操作会同时回滚存储过程1和2吗? - Weng Kit
1个回答

3

SQL Server数据库引擎会忽略提交内部事务的操作。事务的提交或回滚取决于最外层事务的结束时采取的操作。如果外部事务被提交,则内部嵌套事务也将被提交。

嵌套事务


1
现在它可以工作了。我移除了内部事务并使用了try catch。因此,当内部存储过程出错时,外部事务将回滚所有操作。 - Weng Kit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接