named explicit & implicit transactions

2019-08-08 19:01发布

I have encountered a small bug(feature) in the SQL Server 2008.

I have a stored procedure where I begin explicit transaction with the name @tran

.... declare @tran varchar(30) = 'exp_trans';

BEGIN TRAN @tran IF @p_param is null ROLLBACK TRAN @tran ....

The problem is, when I set IMPLICIT_TRANSACTIONS ON and invoke the stored procedure, the flow hits the rollback section, I will receive the error

"Msg 6401, Level 16, State 1, Line 10 Cannot roll back exp_tran. No transaction or savepoint of that name was found."

Is this some sort of feature, or what is actually happening? Thank you in advance

1条回答
女痞
2楼-- · 2019-08-08 19:52

I believe this is happening because of nested transactions and SQL Server 2008 does not support rolling back to an inner transaction when transactions are nested:

Naming multiple transactions in a series of nested transactions with a transaction name has little effect on the transaction. Only the first (outermost) transaction name is registered with the system. A rollback to any other name (other than a valid savepoint name) generates an error. None of the statements executed before the rollback is, in fact, rolled back at the time this error occurs. The statements are rolled back only when the outer transaction is rolled back.

Your transactions are nested because the implicit transactions setting starts one, the begin trans starts the second (nested) transaction. And that makes the rollback to the named transaction fail.

查看更多
登录 后发表回答