I saw similar questions of this, but no one could help me to figure out my problem. So, here is the issue: I have the following statement:
BEGIN TRANSACTION
print @@TRANCOUNT
EXECUTE proc1
print @@TRANCOUNT
COMMIT TRANSACTION
CREATE PROCEDURE proc1 AS
BEGIN
SET XACT_ABORT ON
SAVE TRANSACTION TillOuterMost;
BEGIN TRANSACTION
print @@TRANCOUNT
ROLLBACK TRANSACTION TillOuterMost;
END
GO
When running this I am getting error:
1
2
Msg 266, Level 16, State 2, Procedure proc1, Line 0 [Batch Start Line 12]
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 2.
2
Which means that ROLLBACK TRANSACTION TillOuterMost;
statement didn't decrement transaction count. Later I tried just to remove saved labeled and just used ROLLBACK TRANSACTION. But this rollbacks both inner and outer transactions and gives the following error:
1
2
Msg 266, Level 16, State 2, Procedure proc1, Line 0 [Batch Start Line 11]
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0.
0
Msg 3902, Level 16, State 1, Line 18
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
Note, that in the latter case transaction count has been decremented to 0.
I have also tried this variant which also doesn't help:
CREATE PROCEDURE proc1 AS
BEGIN
SET XACT_ABORT ON
SAVE TRANSACTION OO
BEGIN TRANSACTION
print @@TRANCOUNT
ROLLBACK TRAN OO;
END
GO
BEGIN TRANSACTION AA
print @@TRANCOUNT
EXECUTE proc1
if @@TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION AA;
END
ELSE
BEGIN
COMMIT TRANSACTION AA
END
Still getting error:
1
2
Msg 266, Level 16, State 2, Procedure proc1, Line 0 [Batch Start Line 12]
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 2.
Do you have any idea how this can be resolved?
Every BEIGN must have also an END, in your case a COMMIT
CREATE PROCEDURE proc1 AS
BEGIN
SET XACT_ABORT ON
SAVE TRANSACTION TillOuterMost;
BEGIN TRANSACTION
print @@TRANCOUNT
ROLLBACK TRANSACTION TillOuterMost;
COMMIT
END
BEGIN TRANSACTION
print @@TRANCOUNT
EXECUTE proc1
print @@TRANCOUNT
COMMIT TRANSACTION
1
2
1