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 HandlingChanged language setting to Norsk.NextNewYearEve-----------------------Msg 241, Level 16, State 1, Line 2Conversion failed when converting date and/or time fromcharacter string.DROP VIEW dbo.NextNewYearEve ;Listing 8-1: Language settings can cause certain date queries to fail.The main point is clear: when we develop T-SQL code, we cannot assume that ourqueries or data modifications will always succeed, and we need to be prepared for suchfailures and handle them gracefully. When an unexpected error occurs during datamodification, it is essential that execution of the statement is terminated, the databaseis returned to the state it was in before the statement started, and a message is sent tothe calling client, giving some details of the error that occurred and the action taken asa result. Likewise, if a SELECT fails that is part of a longer transaction that has alreadymodified data, then these modifications must be undone as well.Using Transactions for Data ModificationsIn many cases, during data modifications, we cannot take our database from oneconsistent state to another in a single statement. If a data modification requires morethan one statement to effect the required change, then explicit transactions shouldbe used to ensure that these statements succeed or fail as a unit, and that our errorhandling can handle them as a unit.For example, suppose that we need to log, in one table, all the modifications made toanother table. Listing 8-2 shows the code to create the table to be modified (Codes) andthe table in which the modifications will be logged (CodeDescriptionsChangeLog).257

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

Saved successfully!

Ooh no, something went wrong!