Friday , November 22 2024

Exception Handling(TRY-CATCH) in SQL Server(TSQL)

We can use try-catch blocks in TSQL since SQL Server 2005.

In the try block;

We write the TSQL code that we want to catch if an error occurs.

In the catch block;

We write the TSQL code to run when an error occurs.

TRY-CATCH USAGE:

The following functions are used to get more information about the error we captured in the CATCH block.

ERROR_NUMBER (): Returns the code of the error.

ERROR_MESSAGE (): Returns a detailed description of the error.

ERROR_SEVERITY (): Returns the severity of the error.

ERROR_STATE (): Returns the status number of the error.

ERROR_LINE (): Returns the line in which the error occurred.

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

In the following example, we created an error and read the information about the error.

Likewise, when we run a transaction, we must rollback any operations that are in a possible error. @@TRANCOUNT function returns the number of open transaction.

Loading

About Ahmet KAYMAZ

Leave a Reply

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