CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

How to use Try Catch Block for SQL Transactions in SQL Server 2005 ?
Submitted By Bala Murugan
On 3/11/2010 6:28:51 AM
Tags: CodeDigest,SQL,SQL Server 2005  

How to use Try Catch Block for SQL Transactions in SQL Server 2005?

 

Modern programming languages like C#, java made the exception handling simpler by adding try catch mechanism. The back end systems employed a completely different approach to handle errors and exceptions which is sort of complicated since it mostly deals with error ids and numbers.

 

Microsoft brought the use of try catch mechanisms in SQL Server 2005 for efficient and easy error handling. Like any other statement, the try catch also has Begin -End syntax. Refer below,

BEGIN TRY

//SQL statements

 END TRY
 BEGIN CATCH
//Hanlde errors

 END CATCH

 

The below code snippet will help us to implement a simple transaction and rollback transaction using Try Catch block in SQL server 2005.

CREATE PROCEDURE DoComplextTrans
(@ID int)
AS
BEGIN

 BEGIN TRY


  BEGIN TRANSACTION   


  
  /* Your transactions*/


  
  COMMIT
 END TRY
 
BEGIN CATCH
  IF @@TRANCOUNT > 0
  BEGIN
  /* Error occured*/
  ROLLBACK
  END


  
 END CATCH

END

 

Read here to know more about http://msdn.microsoft.com/en-us/library/ms187967.aspx


 

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..