I want to rollback a transaction after finding an error in my SP, so I found here, the TRANSACTION
block should go inside the TRY
block.
However, when I run that example I am getting:
Msg 6401, Level 16, State 1, Line 16
Cannot roll back MYTRAN. No transaction or savepoint of that name was found.
I wonder if that approach is correct or is backward, I mean the TRY
block should go inside the TRANSACTION
block.
Edit
I am running a very similar query used in the link above.
But just in case the code is
BEGIN TRY
BEGIN TRANSACTION MYTRAN; -- Give the transaction a name
SELECT 1/0 -- Generates divide by zero error causing control to jump into catch
PRINT '>> COMMITING'
COMMIT TRANSACTION MYTRAN;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
BEGIN
PRINT '>> ROLLING BACK'
ROLLBACK TRANSACTION MYTRAN; -- The semi-colon is required (at least in SQL 2012)
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage
END
END CATCH