Surprisingly, I could not find any relevant explanation or documentation for this issue I'm having.
In the case of these SQL statements:
SELECT 1 AS Test INTO #tmpTest BEGIN TRAN SELECT 1 AS Test INTO #tmpTest ROLLBACK TRAN When executed one by one, the SELECT ... INTO at line 3 fails, as expected, with message -
There is already an object named '#tmpTest' in the database.
However, after that, the ROLLBACK statement in line 4 fails:
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
Even though the transaction did BEGIN successfully from line 2.
I've seen SQL Server - transactions roll back on error? but answers don't apply here because the default xact_abort is off. In addition, the answer from Quassnoi contradicts the answer by Raj More.
What's the actual explanation?
SELECT @@TRANCOUNTbefore and after the secondSELECTstatement, then executed line by line. The first one returned (as expected)1, then theSELECTfailed, then the second@@TRANCOUNTreturned0. BUT, wrap the badSELECTin a try/catch, and there's still an open transaction going into theCATCHblock. Fascinating.