Handling SQL Server Errors in Nested Procedures

asic error handling in SQL Server’s programming language, Transact-SQL, is straightforward. But when you nest calls to stored procedures, and the procedures have SQL transactions, error handling becomes much more complex. In this article I’ll show you some tried-and-true models for how to handle errors in nested stored procedures with transactions. Over the past year I’ve worked on two projects that needed a strategy for handling errors in stored procedures where the procedures used transactions. My task was to come up with a way to gracefully exit from the stored procedures when non-fatal errors were detected so I could roll back the transaction. I’ll present the result of that work in the two models you’ll learn about in this article.

So how do you handle errors in your code when an error occurs? Unless it encounters a broken connection, SQL Server will return an error to the client application. When you work directly with your own client or middle-tier code, you have much more control over how you handle errors. So you could just issue all your queries to SQL Server discretely from your client code and let SQL Server errors throw you into your error-catching logic, thereby keeping all your error handling in your own calling code. However, encapsulating database-oriented code in SQL Server stored procedures offers a more efficient and elegant solution. In those cases, you need to consider what to do when SQL Server errors occur.

Let’s look first at some general features of error handling.

Transact-SQL Error Handling
Transact-SQL error handling techniques are simple, but SQL Server’s error-returning behavior can seem confusing and occasionally inconsistent. You can trap some errors in Transact-SQL code, but other errors are fatal to a batch or transaction. When SQL Server encounters a non-fatal error trying to execute a command, the @@ERROR system function captures the error message. If the error is fatal, you cannot catch the error in Transact-SQL at all; you’ll have to rely on your client code’s catch logic.

If a trappable error occurs, the @@ERROR function will have a value greater than 0. SQL Server resets the @@ERROR value after every successful command, so you must immediately capture the @@ERROR value. Most of the time, you’ll want to test for changes in @@ERROR right after any INSERT, UPDATE, or DELETE statement. I prefer to capture the value of @@ERROR into a variable immediately, so I can use it later, as in the following snippet:

   DECLARE @Error int   ...   UPDATE ...   SET @Error = @@ERROR   IF @Error > 0 ...

Because SQL Server resets the @@ERROR with the next successful command, when the IF statement in the code snippet successfully executes, SQL Server will reset @@ERROR back to 0. This can cause a problem if you’re also interested in getting the row count of a command, because most commands will also reset the @@ROWCOUNT system. You can capture them both simultaneously using the SELECT statement as shown in the following snippet:

   DECLARE @Error int, @Rowcount int   ...   UPDATE ...   SELECT @Error = @@ERROR     ,@Rowcount = @@ROWCOUNT   IF @Error > 0 ...     IF @Rowcount = 0 ...

You can also capture @@ERROR to test for SELECT errors, with some limitations. For example, you can trap an error if at runtime some object (table or view) referenced by the SELECT is missing (Transact-SQL error message 208.) However, syntax errors in the SELECT command, or any other error that causes compilation of a batch to stop, are fatal and cannot be trapped.

It’s much more efficient and elegant to encapsulate database-oriented code in SQL Server stored procedures, so you need to consider what to do when errors occur in your stored procedures.

It’s more useful to capture @@ERROR after INSERT, UPDATE, and DELETE statements because, by default, constraint violations are not fatal. Foreign key and check constraints will not be fatal (meaning they will not abort the batch or transaction) unless SET XACT_ABORT is ON (see the section on XACT_ABORT below.)

The number of possible error messages is very large; over 3,800 error messages are stored in the master database’s sysmessages system table (some are actually templates). Unfortunately, only a small number of the error messages are documented in Books Online; you can often get more complete explanations of errors in the Knowledge Base.

You can use the RAISERROR statement to generate your own errors in Transact-SQL code. You can also define your own error messages, starting with number 50001, using the system stored procedure sp_addmessage, which will add a message to the sysmessages table. You can then reference the error message in the RAISERROR statement. However, most developers prefer to insert a string message into the RAISERROR statement, because adding custom messages to the sysmessages table creates an additional dependency of your database on a table outside the database, thereby making it less portable.

Batches and Stored Procedures
SQL Server compiles and executes its code in batches of commands. When you work with SQL Server scripts, you use the GO statement for separating batches (it is not really an executed command.) Every stored procedure, trigger, and user-defined function can each consist of only one batch. SQL Server has some important restrictions on batches. For example, you must make the CREATE PROCEDURE the first statement in a batch, so you can create only one procedure per batch.

It’s possible that an SQL Server error may abort the current batch (stored procedure, trigger, or function) but not abort a calling batch. In this article, I will focus primarily on stored procedures, with some remarks about triggers in the context of transactions.

You should consider two major points when you work with SQL Server stored procedures and errors:

  • Does an SQL Server error abort a called batch or stored procedure?
  • Does the error abort a set of nested (called) stored procedures?

Using Transactions
If you encapsulate any of your operations in database transactions, some errors will abort a transaction while others will not. When working with transactions, consider the following questions:

  • Does the error abort the transaction?
  • What type of transaction is it?
  • Is the XACT_ABORT setting on?

When SQL Server aborts a transaction, it also aborts the current and calling batches or stored procedures. SQL Server has three types of transactions: Autocommit, Explicit, and Implicit.

Autocommit: All data-modification statements such as INSERT, UPDATE, and DELETE occur in a transaction. If you do not explicitly declare a transaction, or if you use an implicit transaction, SQL Server automatically uses a transaction for those commands. That is the autocommit mode. SQL Server ensures these data-modification commands either completely succeed or completely fail. If you update a million rows, and SQL Server cannot complete the update, it will not leave the database only partially updated. This keeps the database in a consistent state and assures the atomicity of the transaction. That is, all the steps of a transaction as a group must complete, or everything gets rolled back.

The number of possible error messages is very large; over 3,800 error messages are stored in the master database’s sysmessages system table. Unfortunately, only a small number of the error messages are documented in Books Online.

Explicit: You can explicitly begin a Transact-SQL transaction with BEGIN TRANSACTION, optionally label it, and end the transaction with either COMMIT TRANSACTION or ROLLBACK TRANSACTION?but not both. A COMMIT statement instructs SQL Server to commit your changes, while a ROLLBACK statement results in all changes being removed. SQL Server can do this because it first writes all data changes to the transaction log before it changes any actual database data. If SQL Server needs to restore any data to its original state because of an error or a ROLLBACK, it can recover that data from the transaction log.

When you explicitly begin a transaction, the @@TRANCOUNT system function count increases from 0 to 1; when you COMMIT, the count decreases by one; when you ROLLBACK, the count is reduced to 0. As you see, the behavior of COMMIT and ROLLBACK is not symmetric. If you nest transactions, COMMIT always decreases the nesting level by one, as you can see illustrated in Figure 1. The ROLLBACK command, on the other hand, rolls back the entire transaction, illustrated in Figure 2. This asymmetry between COMMIT and ROLLBACK is the key to handling errors in nested transactions.

The Single-Level Model
In the single-level model, if a transaction is already in place, the procedure will not start a new one; instead, the transaction level remains unchanged (i.e., at a single level). If it has to roll back and it did not start the transaction, the procedure raises an error and returns an error message to the caller. In this model, the procedures do not take the transaction level beyond 1.

The basic strategy for the single-level model is to start by declaring a local variable to record whether this procedure should begin a transaction or not. If the transaction count is 0 when the transaction starts, the procedure issues a BEGIN TRANSACTION.

If you call another stored procedure, you should capture both the return value of the stored procedure and the value of @@ERROR. If the return value from the called procedure is -1, or if @@ERROR was greater than 0, the procedure assumes that an error has occurred that requires us to stop further processing and exit through an error path. If the return value from the called procedure is -1, the called procedure has already raised an error so there’s no need to raise one again. However, if the stored procedure call failed, or there was a non-trappable error in the called procedure, you should raise an error and report it to the caller so that you’ll know what procedure actually failed.

A stored procedure transaction should be rolled back at the same level at which it was started, so only the calling procedure that starts a transaction should ever roll back.

If the stored procedure has its own critical event, such as an INSERT, UPDATE, or DELETE, then you should test that command. Again, capture the value of @@ERROR; if it is greater than zero, the procedure should abort its processing. In this case you should raise an error indicating where the problem occurred, and exit through the error path.

In the procedure’s error exit path, you test whether this procedure began a transaction. If it did, then the procedure issues a ROLLBACK, In either case the procedure should RETURN a -1 to tell a calling procedure that it should also exit through its error exit path.

When no errors occur, the procedure should exit through a normal exit path; if it started a transaction, the procedure should COMMIT and return a 0. If it did not start a transaction, there’s no need to issue a COMMIT.

Listing 1 contains the outline of a stored procedure using the single-level model. It shows the code for the outermost procedure, but the same code works at any level. If a procedure is at the innermost level of a set of nested procedures, you can remove the code that traps for calling a stored procedure.

If a procedure does not begin a transaction, set the @LocalTran flag to 0. The procedure will never execute either a COMMIT or a ROLLBACK, but will still trap for errors calling other stored procedures and exit out its error path (the ErrExit label) if it detects a failure from called procedures.

I’ve used this model in production a couple times now, and it works well. When SQL Server returns errors from low in the procedure nesting, the error messages help to easily pinpoint the location.

The Multi-Level Model
SQL Server MVP Fernando Guerrero pointed out to me that there is an alternative approach that does permit transaction nesting. The overall algorithm is very similar. In the multi-level model, a procedure may begin a new transaction; but if it detects the need to roll back and the @@TRANSACTION value is greater than 1, it raises an error, returns an error message to the caller, and issues a COMMIT instead of a ROLLBACK. The multi-level model allows transaction levels to increase.

Both models only roll back a transaction at the outermost level. While the multi-level model explicitly begins a transaction, it makes sure that every procedure below the outermost one issues a COMMIT rather than a ROLLBACK, so the @@TRANCOUNT level is properly decremented even if the procedures are all exiting through their error path.

In this model, you do not need to keep track of whether this procedure began a transaction. Instead, just issue the BEGIN TRANSACTION. The error handling for calling other stored procedures and issuing critical commands remains the same.

If the procedure exits via its normal exit path, it should just issue a COMMIT and return a 0. But if the procedure exits out its error path (through its ErrExit label), there are two options. If the value of @@TRANCOUNT is greater than 1, this procedure did not initiate the transaction, so it should just COMMIT and return a -1. If @@TRANCOUNT is exactly 1, this procedure did initiate the transaction, so it issues a ROLLBACK and returns -1.

Listing 2 shows sample code using this strategy.

Again, if you are not calling other procedures, you can just remove the related code. However, if you are not using a transaction in this procedure, you’ll also need to remove the COMMIT and ROLLBACK conditions from the code.

Comparing the Two Models
What’s interesting about both models is that they can inter-operate. Both follow the rule that they will not roll back a transaction if they did not initiate it, and they both always leave the transaction level of a stored procedure the same as when they entered the transaction.

The advantage of the multi-level approach is that you can use code that is somewhat simpler. The advantage of the single-level approach is that you can easily turn the transaction handling on or off without removing or commenting out lines of code.

I’ve used the single-level model in two applications and it is working fine. Whichever model you choose, you’ll have a solid approach to handling Transact-SQL errors in nested procedures that use transactions.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet

payment via phone

7 Ways Technology Has Changed Traditional Payments

In today’s digital world, technology has changed how we make payments. From contactless cards to mobile wallets, it’s now easier to pay for goods and services without carrying cash or using a checkbook. This article will look at seven of the most significant ways technology has transformed traditional payment methods.

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap