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 2: Code Vulnerabilities due to SQL Server Misconceptionsthere are no other possible plans). As the table is scanned, the conditions oninteger columns are evaluated first because integer comparisons are cheaper thanDATETIME conversions.In any event, after creating the new index, the optimizer has decided that the new indexMessages_SenderID_MessageDate is selective enough to be used in our query.So the database engine begins a range scan of the index Messages_SenderID_MessageDate on the condition SenderID=123. For each index entry that satisfiesthis condition, it also evaluates the condition CAST(MessageDateAsVarcharColumnAS DATETIME)='20090707' to narrow down the search, because the columnMessageDateAsVarcharColumn is also stored in the same index entry.Let me repeat my disclaimer: there is no guarantee that this query will succeed or fail onyour server the way it does on mine. We cannot assume that conditions in the WHEREclause execute in any particular order. We have learned that the safe way to guaranteethe order in which conditions evaluate is to use CASE expressions.SET, SELECT, and the dreaded infinite loopWe cannot assume that SET and SELECT always change the values of variables. If werely on that incorrect assumption, our code may not work as expected, so we need toeliminate it. Listing 2-9 demonstrates a case where SELECT leaves the value of a variableunchanged, if the result set is empty.SET NOCOUNT ON ;DECLARE @i INT ;SELECT @i = -1 ;SELECT @i AS [@i before the assignment] ;SELECT @i = 1WHERE 1 = 2 ;SELECT @i AS [@i after the assignment] ;64

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

Saved successfully!

Ooh no, something went wrong!