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 3: Surviving Changes to <strong>Database</strong> ObjectsEXEC dbo.SelectCode @Code = '1234567890' ;Code Description---------- ---------------------12345 Description for 12345Listing 3-31: The unchanged stored procedure retrieves the wrong row.Such bugs are quite subtle, and may take considerable time to troubleshoot. How canwe prevent such errors, except for manually referring to a data dictionary every timewe change column types? The best way, in my opinion, is to document the requirementthat the type and lengths of our stored procedure parameters must match the type andlengths of our columns and then incorporate this requirement into a boundary case unittest, to protect us from such errors.SummaryIn this chapter, we have seen how changes in database objects may break our code, anddiscussed several defensive techniques that improve the robustness of our code, so thatit better survives changes in other database objects. Specifically, I hope you've learnedthe following lessons in defensive programming:• how to test the continuing validity of your assumptions about the characteristics ofthe underlying primary and unique keys• why using SET is generally safer than using SELECT when assigning valuesto variables• the importance of explicitly named parameters in stored procedure calls• the need to qualify column names in queries• why NOT EXISTS leads to more resilient queries than NOT IN• the importance of testing and validating even the "obvious" assumptions,such as the need for the types and length of parameters to match those of theunderlying columns.103

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

Saved successfully!

Ooh no, something went wrong!