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 1: Basic <strong>Defensive</strong> <strong>Database</strong> <strong>Programming</strong> TechniquesSELECT Code ,DescriptionFROM dbo.Codes ;ROLLBACK ;AND NumValues = 1 ;Listing 1-31: Using an analytical function to detect and ignore ambiguities whenusing UPDATE…FROM.SummaryThe goal of this chapter was to introduce, by way of some simple examples, someof the basic ideas that underpin defensive database programming. It is vital that youunderstand and document the assumptions that underpin your implementation, testthem to ensure their validity, and eliminate them if they are not. It is also vital thatyou consider as many use cases as possible for your code, and ensure it behavesconsistently in each case. Where inconsistencies or incorrect behavior are found, thedefensive programmer will not only fix the offending module, but also test all othermodules that might suffer from a similar problem and proactively safeguard against it.Along the way, I hope you've learned the following specific lessons in defensiveprogramming:• how to use complex patterns to improve the robustness of LIKE searches• how to avoid potential difficulties with SET ROWCOUNT• the importance of safe date formats and of explicitly specifying the required formatwhen converting dates• how to avoid dangerous ambiguity when performing updates by, for example:• using MERGE, in SQL Server 2008• using subqueries, pre-SQL Server 2008.• how to use subqueries or the COUNT(*) OVER analytic function to improve therobustness of modifications when using UPDATE...FROM, or updating inline views,so that ambiguous updates are ignored.55

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

Saved successfully!

Ooh no, something went wrong!