17.07.2015 Views

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8: <strong>Defensive</strong> Error HandlingCode Description---------- ----------------------------------------ILother value(1 row(s) affected)Code---------- ----------------------------------------(0 row(s) affected)Listing 8-5: An INSERT into CodeDescriptionsChangeLog fails, but theUPDATE of Codes succeeds, and we end up with an UPDATE thathas not been logged.In order to avoid this situation, we need to begin a transaction, attempt to do bothmodifications, determine whether or not both completed successfully, and commit thetransaction only if both modifications succeeded. If either modification failed, we needto roll back the transaction, as part of our error handling. T-SQL allows several ways toaccomplish that. Let's begin with the simplest approach: using transactions along withthe XACT_ABORT setting.Using Transactions and XACT_ABORT toHandle ErrorsIn many cases, we do not need sophisticated error handling. Quite frequently, all weneed to do in case of an error, is roll back all the changes and throw an exception, so thatthe client knows that there is a problem and will handle it. In such situations, a perfectlyreasonable approach is to make use of the XACT_ABORT setting.By default, in SQL Server this setting is OFF, which means that in some circumstancesSQL Server can continue processing when a T-SQL statement causes a run-time error.In other words, for less severe errors, it may be possible to roll back only the statementthat caused the error, and to continue processing other statements in the transaction.262

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!