How can I ensure that nested transactions are committed independently of each other?

醉酒当歌 提交于 2019-12-05 03:27:43
gbn

First off, there is no such thing as a nested transaction in SQL Server

However, you can use SAVEPOINTs as per this example (too long to reproduce here sorry) from fellow SO user Remus Rusanu

Edit: AlexKuznetsov mentioned (he deleted his answer though) that this won't work if a transaction is doomed. This can happen with SET XACT_ABORT ON or some trigger errors.

From BOL:

ROLLBACK TRANSACTION without a savepoint_name or transaction_name rolls back to the beginning of the transaction. When nesting transactions, this same statement rolls back all inner transactions to the outermost BEGIN TRANSACTION statement.

I also found the following from another thread here:

Be aware that SQL Server transactions aren't really nested in the way you might think. Once an explict transaction is started, a subsequent BEGIN TRAN increments @@TRANCOUNT while a COMMIT decrements the value. The entire outmost transaction is committed when a COMMIT results in a zero @@TRANCOUNT. But a ROLLBACK without a savepoint rolls back all work including the outermost transaction.

If you need nested transaction behavior, you'll need to use SAVE TRANSACTION instead of BEGIN TRAN and use ROLLBACK TRAN [savepoint_name] instead of ROLLBACK TRAN.

So it would appear possible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!