If I am coding a SQL Server (2008r2) procedure, and I wrap it in a transaction, do I need to explicitly enclose it in a try..catch block, and then explicitly call rollback in the catch block, or will it exit and rollback the same on its own?
i.e.:
How does this:
begin transaction
begin try
delete from....
insert into...
end try
begin catch
rollback transaction
return
end catch
commit transaction
Compare with:
begin transaction
delete from....
insert into...
commit transaction
Thank you for any help.
The answer to your question depends on the
SET XACT_ABORTsetting:For example, try the following code. The first division by 0 raises an error but continues execution. The second division by zero raises an error and halts execution:
If XACT_ABORT is ON, then errors will abort the transaction, and you don’t need a TRY / CATCH.
If XACT_ABORT is OFF, you will need to check the status of each statement to see if an error occurred:
However, if you ever find a case where you need to TRY / CATCH, you may need to do something special when the error occurs. If so, don’t forget to TRY / CATCH the exception handling: