Wednesday, 2 May 2012

SQL Server Exceptional Handling


The exceptional handling in SQL is so simple after SQL server 2005 version. By using a simple try catch statement as we do in VB.net. Even the syntax looks so similar to that of VB.net program.

Syntax:

Begin Try
Begin Transaction
   //Your Code
Commit Transaction
End Try
Begin Catch
Rollback Transaction
End Catch

The SQL script execute without any issues if everything goes fine within Try block and if there is any error occurs it will go to Catch block and rollback the executed script. This is so useful for DML script execution and Stored Procedures which perform DML operation.

To trap the error in the catch block we can use below built in functions available in the SQL
  • ERROR_NUMBER() - returns the number of the error.
  • ERROR_SEVERITY() - returns the severity.
  • ERROR_STATE() - returns the error state number.
  • ERROR_PROCEDURE() - returns the name of the stored procedure or trigger where the error occurred.
  • ERROR_LINE() - returns the line number inside the routine that caused the error.
  • ERROR_MESSAGE() - returns the complete text of the error message.


Example:

Begin Try
Begin Transaction
Insert into test_table values (key,Foreign_key,textvalue1, textvalue2)
Commit Transaction
End Try
Begin Catch
Rollback Transaction
         Print “Error Number:” + ERROR_NUMBER ()
         Print “Error Message:” + ERROR_MESSAGE ()
End Catch

If there is any foreign key violation while inserting the value it will throw the below error.

Error Number:  1
Error Message:  Foreign key violation while inserting record into test_table record.

No comments:

Post a Comment