Saturday, April 28, 2012

TRY-CATCH for the T-SQL

Just as a reminder for those who still don't know, since SQL Server 2005 it is possible to write TRY-CATCH block, just as it is a common practice in a modern programming language such as Java or C#.


The concept is useful for catching an irregularity during the execution and selectinthe error-handling branch of the script.


For example, a transaction script could be written as follows:


BEGIN TRANSACTION;
BEGIN TRY
  -- T-SQL statements...
END TRY
BEGIN CATCH
  -- Your error handling T-SQL statements...
  IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
END CATCH;


IF @@TRANCOUNT > 0
  COMMIT TRANSACTION;


It is really that simple.


For more detailed information on this T-SQL construct, take a look at the official article.