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> ErrorHandlingThe ability to handle errors is essential in any programming language and, naturally, wehave to implement safe error handling in our T-SQL if we want to build solid SQL Servercode. SQL Server 2005 (and later) superseded the old-style @@Error error handling, withthe TRY…CATCH blocks that are more familiar to Java and C# programmers.While use of TRY…CATCH certainly is the best way to handle errors in T-SQL, it is notwithout difficulties. Error handling in T-SQL can be very complex, and its behavior cansometimes seem erratic and inconsistent. Furthermore, error handling in Transact SQLlacks many features that developers who use languages such as Java and C# take forgranted. For example, in SQL Server 2005 and 2008, we cannot even re-throw an errorwithout changing its error code. This complicates handling errors, because we haveto write separate conditions for detecting exceptions caught for the first time, and fordetecting re-thrown exceptions.This chapter will demonstrate simple SQL Server error handling, using XACT_ABORTand transactions; it will describe the most common problems with TRY…CATCH errorhandling, and advocate that the defensive programmer, where possible, shouldimplement only simple error checking and handling in SQL Server, with client-sideerror handling used to enforce what is done on the server.Prepare for Unanticipated FailureAny statement can, and at some point inevitably will, fail. This may seem to be astatement of the obvious, but too many programmers seem to assume that, oncetheir code "works," then the data modifications and queries that it contains willalways succeed.In fact, data modifications can and do fail unexpectedly. For example, the data maynot validate against a constraint or a trigger, or the command may become a deadlockvictim. Even if the table does not have any constraints or triggers at the time the code is255

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

Saved successfully!

Ooh no, something went wrong!