I created the following stored procedure.
alter proc test as if @@trancount = 0 begin begin tran test; end; else begin save tran test; end; -- ...... if @@trancount > 0 begin print formatmessage('trancount %d', @@trancount); commit tran test; print formatmessage('commit %d', @@trancount); end; It works when exec dbo.test. However, the following code got the following error?
begin tran; exec dbo.test; rollback; -- Or commit Msg 266, Level 16, State 2, Procedure test, Line 19
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0.
Msg 3902, Level 16, State 1, Line 22
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
If @@TRANCOUNT has a different value when a stored procedure finishes than it had when the procedure was executed, an informational error (266) occurs.Likewise, since stored procedures are technically batches in themselves, and you're skipping the part where you begin the transaction, it will throw an error for that as well.