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 HandlingDoomed transactionsThere is another serious problem with T-SQL TRY…CATCH blocks: in some cases anerror that occurred inside a TRY block is considered so severe that the whole transactionis doomed, or, in other words, it cannot be committed. Theoretically, the concept ofdoomed transactions makes perfect sense. Unfortunately, some really trivial errors, suchas conversion errors, render transactions doomed if we use TRY…CATCH provided byT-SQL. For example, consider the transactions shown in Listing 8-20. The first attemptsto perform a 1/0 calculation, and the second, to convert a strong to an integer. We donot want to roll back the whole transaction if an error occurs, so we set XACT_ABORTto OFF.SET XACT_ABORT OFF ;SET NOCOUNT ON ;BEGIN TRANSACTION ;SELECT 1 ;GOBEGIN TRY ;SELECT 1 / 0 ;END TRYBEGIN CATCHPRINT 'Error occurred' ;SELECT error_message() AS ErrorMessage ;END CATCH ;GOIF @@TRANCOUNT 0BEGIN ;COMMIT ;PRINT 'Committed' ;END ;GOBEGIN TRANSACTION ;SELECT 1 ;GOBEGIN TRY ;281

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

Saved successfully!

Ooh no, something went wrong!