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 HandlingComplete testing would include:• making sure that, if both the modification of the Codes table and the INSERT intothe CodeDescriptionsChangeLog table succeed, then the transaction commitsand both changes persist• verifying that, if an UPDATE of the Codes table fails, then the transaction rolls back.To reproduce a failure, we can use a similar technique; a CHECK constraint thatmakes sure all UPDATEs against the Codes table fail• invoking the stored procedure without an outstanding transaction, when@@TRANCOUNT is 0. In that case, we shall have to explicitly drop the CHECKconstraint which we create in our test.I encourage you to tweak Listing 8-7 and try out these other tests. In many cases,this simple approach of setting XACT_ABORT to ON and using an explicit transactionfor modifications gets the job done without much effort. We should use this simpleand robust approach unless we really need more sophisticated functionality from ourerror handling.If we really want to do some more complex error handling on the server, usingT-SQL, then we should use TRY…CATCH blocks, which are available in SQL Server 2005and upwards.Using TRY…CATCH blocks to Handle ErrorsTo handle errors in T-SQL modules, in SQL Server 2005 and upwards, we can useTRY…CATCH blocks. If any command inside the TRY block raises an error, the executionof the TRY block terminates immediately, which is similar to the behavior under theXACT_ABORT setting. But, unlike with XACT_ABORT, where the whole batch terminates,only the execution of the code inside the TRY block terminates, and the CATCH blockbegins to execute.In cases where you are aware that a certain specific error could occur, your errorhandlingstrategy can be different. You may attempt to add code to your CATCH blockthat corrects the error, or at least allows processing to continue. In these cases, it makesmore sense to have XACT_ABORT set to OFF, so that you can handle the errors, andinform the calling client of what happened, without rolling back the entire batch.266

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

Saved successfully!

Ooh no, something went wrong!