Skip to main content

#SQL Try...Catch

Microsoft have introduced the TRY & CATCH syntax (TAC) for error handling is T-SQL, in SQL server 2005. The .NET must have used this syntax before also, as this TAC was initially introduced and now they are introducing this in SQL also

How it works
As I have mentioned this TAC block is very similar to what be use in other.net languages. The idea is fairly simple

When an error condition is detected in a Transact-SQL statement contained in a TRY block, control is passed to a CATCH block where it can be processed.

Begin Try 
     The_Query_for_which_we_need_to_do_the_ Error_Handling 
End Try 
Begin Catch 
   If there is some error in the query within the Try block, this flow 
  will be passed to this Catch block. 
End catch 

If there are no errors inside the TRY block, control passes to the statement immediately after the associated END CATCH statement. If the END CATCH statement is the last statement in a stored procedure or trigger, control is passed to the statement that invoked the stored procedure or trigger.

BEGIN TRY           
      Print ' I am level 1 '
          BEGIN TRY
            Print ' I am level 2 '
            SELECT 1/0;    
          END TRY
          BEGIN CATCH    
   SELECT 
   ERROR_NUMBER() AS ErrorNumber,
   ERROR_SEVERITY() AS ErrorSeverity,
   ERROR_STATE() as ErrorState,
   ERROR_PROCEDURE() as ErrorProcedure,
   ERROR_LINE() as ErrorLine,
   ERROR_MESSAGE() as ErrorMessage;   
    Print ' I am going out level 2   ' 
         END CATCH
    Print ' I am level 1 again '    
END TRY
BEGIN CATCH
    -- Execute the error retrieval routine.
        SELECT 
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() as ErrorState,
        ERROR_PROCEDURE() as ErrorProcedure,
        ERROR_LINE() as ErrorLine,
        ERROR_MESSAGE() as ErrorMessage;    

END CATCH

OUTPUT
 I am level 1 
 I am level 2 
----------- 
(0 row(s) affected)
ErrorNumber ErrorSeverity ErrorState ErrorProcedure ErrorLine ErrorMessage
8134        16            1          NULL               5     Divide by zero 
                                                            error encountered. 
(1 row(s) affected) 
 I am going out level 2   
 I am level 1 again 


In the code above the error is thrown from the Level 2 TAC block 

Error Functions

TRY…CATCH uses error functions to capture error information.

ERROR_NUMBER() returns the error number.

ERROR_MESSAGE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters such as lengths, object names, or times.

ERROR_SEVERITY() returns the error severity.

ERROR_STATE() returns the error state number.

ERROR_LINE() returns the line number inside the routine that caused the error.

ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred.


Error information is retrieved using these functions from anywhere within the scope of the CATCH block of a TRY…CATCH construct. The error functions will return NULL if called outside the scope of a CATCH block. Error functions can be referenced inside a stored procedure and can be used to retrieve error information when the stored procedure is executed within the CATCH block. By doing this, it will not be necessary to type error handling code in every CATCH block.

Comments

Popular posts from this blog

Use Log4Net in C# windows form Application

we are going to learn on how to use the Log4Net library for creating logs. Create a new windows form application in VS. Install Log4Net library Add to AssemblyInfo.cs  Configure in  App.config Use in code  Install Log4Net library Then install the Log4Net library from the Nuget Package library.           log4net by The Apache software foundation 2.0.8 (i installed the latest). Add to AssemblyInfo.cs  After installing this package, open up AssemblyInfo .cs file under the Properties folder and add the log4net assembly information into it (under the other assembly information.).    [assembly: log4net.Config.XmlConfigurator(Watch= true )]  Configure in  App.config Now, open the App.config file and enter required details for LogNet to work. <configSections>       <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2....

#SQL: How to Drop Database in SQL Server by Closing Existing Connections

How to Drop Database in SQL Server when the users are connected to a SQL Server Database. You may need to closing existing connections in a database before restoring the database, before detaching database, get database in SINGLE_USER mode etc. If you try dropping a database when users are connected to the SQL Server Database you will receive the below mentioned error message. Error Message Drop failed for Database 'RajDB'. (Microsoft.SqlServer.Smo) Cannot drop database "" because it is currently in use. (Microsoft SQL Server, Error: 3702) USE [master] GO ALTER DATABASE RajDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE GO /* Query to Drop Database in SQL Server  */ DROP DATABASE RajDB GO