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 2: Code Vulnerabilitiesdue to SQL ServerMisconceptionsIn Chapter 1, we discussed several examples where we could choose whether to ensurethat an assumption that underpinned our code implementation was always true, or toeliminate that assumption, if possible. However, certain vulnerabilities occur due to abasic misunderstanding of how the SQL Server engine, or the SQL language, work. Suchvulnerabilities should always be eliminated, or they will ultimately lead to code failure.This chapter will discuss the following three, very common, misconceptions:• WHERE clause conditions will always be evaluated in the same order – a commoncause of intermittent query failure• SET and SELECT always change the values of variables – this false assumption canlead to the dreaded infinite loop• Data will be returned in some "natural order" – another common cause ofintermittent query failure.In each case we'll examine how, with simple defensive coding techniques, we canimprove the quality and resilience of our database code.Conditions in a WHERE clause can evaluate in anyorderQuite a few languages explicitly guarantee that logical expressions will evaluatein a certain order, from left to right. SQL is not one of them. Never assume that theconditions in your WHERE clause will evaluate in the left-to-right order in which youlist them. If your code relies on the WHERE clause conditions being evaluated in a givenorder, then the resulting query is unsafe.57

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

Saved successfully!

Ooh no, something went wrong!