T-SQL: Try/Catch Pattern

Here’s a simple try/catch pattern for a SQL Server query to help roll back a transaction when something goes awry:

BEGIN Tran;
 
BEGIN Try
 -- do stuff
END Try
BEGIN Catch
  IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
    Throw
END Catch
 
IF @@TRANCOUNT > 0
  Commit TRANSACTION;

Hope this helps!

This entry was posted in MS SQL Server, T-SQL. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *