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 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?
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.
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
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.
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
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
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:
What We Should Expect from Cell Phone Tech in the Near Future
The earliest cell phones included boxy designs full of buttons and antennas, and they only made calls. Needless to say, we’ve come a long way from those classic brick phones
The Best Mechanical Keyboards For Programmers: Where To Find Them
When it comes to programming, a good mechanical keyboard can make all the difference. Naturally, you would want one of the best mechanical keyboards for programmers. But with so many
The Digital Panopticon: Is Big Brother Always Watching Us Online?
In the age of digital transformation, the internet has become a ubiquitous part of our lives. From socializing, shopping, and learning to more sensitive activities such as banking and healthcare,
Embracing Change: How AI Is Revolutionizing the Developer’s Role
The world of software development is changing drastically with the introduction of Artificial Intelligence and Machine Learning technologies. In the past, software developers were in charge of the entire development
The Benefits of Using XDR Solutions
Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved
How AI is Revolutionizing Fraud Detection
Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across
Companies Leading AI Innovation in 2023
Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several
Step-by-Step Guide to Properly Copyright Your Website
Creating a website is not easy, but protecting your website is equally important. Implementing copyright laws ensures that the substance of your website remains secure and sheltered. Copyrighting your website
Fivetran Pricing Explained
One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of
Kubernetes Logging: What You Need to Know
Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes
Why Is Ransomware Such a Major Threat?
One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing
Tools You Need to Make a Data Dictionary
Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as