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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8: <strong>Defensive</strong> Error HandlingNow return to Tab 1, and execute the commented UPDATE against the Codes table,from Listing 8-10, including the COMMIT. As soon as this code tries to execute, adeadlock is detected. SQL Server chooses our stored procedure execution from Tab 2 asthe deadlock victim, since we deliberately contrived for this to be the case. Thetransaction in our TRY block is rolled back, but then our CATCH block is executedand we try to execute our stored procedure again. This time, since Tab 1 has nowcommitted, the modification succeeds. The output from Tab 2 is shown in Listing 8-12.Rolling backEncountered a deadlock(1 row(s) affected)(1 row(s) affected)Modifications succeededCode Description---------- -----------------------------------IL ?(1 row(s) affected)Code---------- -----------------------------------ILIL, Ill.IL Illinois, ?Listing 8-12. Tab 2, output from execution of the stored procedure.Note also, however, that the UPDATE we execute from Tab 1 is "lost;" its changes wereoverwritten when the retry succeeded.From these examples, we have learned the following:• if several modifications must succeed or fail together, use transactions, and roll themodification back, as a unit, if any one of them fails272

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

Saved successfully!

Ooh no, something went wrong!