Stored Procedures  «Prev  Next»

Lesson 9Stored Procedure Error Handling
ObjectiveDescribe how to implement error handling in your stored procedures.

Stored Procedure Error Handling

Implementing error handling in a stored procedure in SQL Server 2019 is a critical aspect of robust database programming. It ensures that your procedures behave predictably and provide meaningful feedback in the face of unexpected conditions or failures. The primary mechanism for error handling in SQL Server is the `TRY...CATCH` construct. Here's how to effectively use it:
  1. Understanding TRY...CATCH:The `TRY...CATCH` construct allows you to separate code into two sections: the `TRY` block, which contains the code that might cause an exception, and the `CATCH` block, which contains code to handle the exception. If an error occurs in the `TRY` block, control is passed to the corresponding `CATCH` block.
  2. Implementing TRY...CATCH:
    • TRY Block:Enclose the main logic of your stored procedure inside the `TRY` block. This includes data manipulation statements like `INSERT`, `UPDATE`, `DELETE`, and also `SELECT` statements.
    • CATCH Block:This block is executed only when an error occurs in the `TRY` block. Inside the `CATCH` block, you can retrieve error information using functions like `ERROR_NUMBER()`, `ERROR_MESSAGE()`, etc. You can log these details for debugging purposes or use them to inform the user about the nature of the error.
  3. Transaction Management:In database operations, maintaining data integrity is crucial. Use transactions within your `TRY...CATCH` blocks. If an error occurs, you can roll back the transaction in the `CATCH` block to ensure that your database remains consistent.
  4. Raising Custom Errors:Sometimes, you might want to generate and throw custom errors based on specific conditions. Use `RAISERROR` or `THROW` statements to achieve this. `THROW` is preferred in SQL Server 2012 and later versions as it is more versatile.
  5. Nested TRY...CATCH Blocks:In complex procedures, you might have nested `TRY...CATCH` blocks. Be mindful of how errors propagate in these scenarios. An error in an inner block can be caught by an outer block if not handled in the inner block.
  6. Error Logging:Consider implementing error logging within your `CATCH` block. Log errors to a table or an external system for later analysis. This can help in diagnosing issues post-failure.
  7. Best Practices:
    • Keep your `TRY` block as short as possible.
    • Avoid writing overly complex `CATCH` blocks; they should handle the error gracefully and exit.
    • Always re-throw critical errors that you cannot handle.
    • Test your error handling thoroughly with different scenarios to ensure reliability.

Here is a basic template for using `TRY...CATCH` in a SQL Server stored procedure:
        -- Your SQL Code goes here
        -- Example: INSERT, UPDATE, DELETE operations
        -- Handle the error
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
        DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
        DECLARE @ErrorState INT = ERROR_STATE();

        -- Log error details or inform the user
        RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);

        -- Optional: Rollback transaction if necessary
In conclusion, effective error handling in SQL Server 2019 stored procedures involves careful planning and implementation of the `TRY...CATCH` blocks, transaction management, and adherence to best practices. This approach not only helps in preventing data corruption but also aids in diagnosing issues when they arise, making your database applications more reliable and maintainable.

Save Time Writing

Why are Stored procedures susceptible to errors?

Stored procedures can be particularly susceptible to errors because of the following factors:
  1. Code volume and complexity: Because a stored procedure generally consists of many Transact-SQL statements, there is a very real possibility that an error will occur. Also, the more complex a Transact-SQL statement gets, the more chance there is for error.
  2. Location: Stored procedures are compiled on the server. This means that another SQL programmer could drop one of the tables referenced by your stored procedure without your knowledge. Even if you did not have an error before you executed the stored procedure, you sure do now.

Are you convinced you that errors can occur?

Detecting Errors

Detecting errors is quite simple. Use the global function @@error directly after a Transact-SQL statement. If @@error contains a value of 0, then all is fine. If @@error contains a value other than 0, then an error occurred in the last statement.

Handling errors

Once an error has been detected, you can decide how to handle it. Handling errors is nothing more than detecting that an error occurred and dealing with it in some way. For example, you might not care that an error occurred, and processing can continue. On the other hand, if an error occurs, especially at a given point in the stored procedure, you must abort because continuing processing would yield invalid data. This is generally known as a fatal error . When an error occurs, you have several options, including:
  1. Doing nothing
  2. Raising an error
  3. Exiting the stored procedure

Raising an error

The following Carousel detects and raises an error that has occurred in a stored procedure:

After the select statement.
1) After the select statement.

the @@error global function is checked
2) the @@error global function is checked

If there are any errors, an error is raised to the calling program of the stored procedure
3) If there are any errors, an error is raised to the calling program of the stored procedure

Remember from prior modules, that if you wish to execute more than one Transact-SQL statement as a result of the IF condition
4) Remember from prior modules, that if you wish to execute more than one Transact-SQL statement as a result of the IF condition

Exiting the stored procedure

To exit from a stored procedure unconditionally and immediately, you use the RETURN Transact-SQL statement. Following the RETURN statement, you can specify code that your calling procedure can check. This code has no significance to SQL Server 2012. The return code is significant only to you. For example, this statement exits a stored procedure with a value of 0:


This is an example of how you would use the RETURN statement:
CREATE PROCEDURE usp_GetLastName @EmployeeID int
SELECT LastName 
FROM employees  
WHERE EmployeeID = @EmployeeID   
IF @@error <> 0 
RAISERROR (‘Error Occurred’, 16, 1) 

In the code above, if no error occurs, the stored procedure returns with a status of 0. Otherwise, the stored procedure returns with a status of 1. In the next lesson, you will learn about and practice using output parameters.