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 1: Basic <strong>Defensive</strong> <strong>Database</strong> <strong>Programming</strong> TechniquesDefending Against Cases of Unintended UseAll too often, we consider our code to be finished as soon as it passes a few simple tests.We do not take enough time to identify and test all possible, reasonable use cases for ourcode. When the inevitable happens, and our code is used in a way we failed to consider,it does not work as expected.To demonstrate these points, we'll consider an example that shows how (and how not)to use string patterns in searching. We'll analyze a seemingly working stored procedurethat searches a Messages table, construct cases of unintended use, and identify animplicit assumption on which the implementation of this procedure relies. We will thenneed to decide whether to eliminate the assumption or to guarantee that it always holds.Either way, we will end up with a more robust procedure.Listing 1-1 contains the code needed to create a sample Messages table, which holdsthe subject and body of various text messages, and load it with two sample messages. Itthen creates the stored procedure, SelectMessagesBySubjectBeginning, whichwill search the messages, using a search pattern based on the LIKE keyword. The storedprocedure takes one parameter, SubjectBeginning, and is supposed to return everymessage whose subject starts with the specified text.CREATE TABLE dbo.Messages(MessageID INT IDENTITY(1,1) NOT NULLPRIMARY KEY,Subject VARCHAR(30) NOT NULL ,Body VARCHAR(100) NOT NULL) ;GOINSERT INTO dbo.Messages( Subject ,Body)SELECT 'Next release delayed' ,'Still fixing bugs'UNION ALL22

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

Saved successfully!

Ooh no, something went wrong!