SQL Server – Try Catch Statement Syntax

I’m sure there are more complexities to this – but this seems to work well in most applications

[code:tsql]

BEGIN TRY

 BEGIN TRANSACTION
 
 — Do whatever you need to do
 

 COMMIT TRANSACTION

END TRY

BEGIN CATCH

 — Rollback if in a transaction

 IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
 
 — Do whatever error logging you need to do

END CATCH

[/code]

 

Leave a Reply

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