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 Vulnerabilities due to SQL Server MisconceptionsSELECT MessageID ,SenderID ,ReceiverID ,MessageDateAsVarcharColumn ,SomeMoreDataFROM dbo.MessagesWHERE CAST(MessageDateAsVarcharColumn AS DATETIME) ='20090707';-- your actual error message may be different-- depending on the version of SQL ServerMsg 241, Level 16, State 1, Line 1Conversion failed when converting datetime from characterstring.Listing 2-3: A simple query against the Messages table fails with a conversion error.Clearly, we need to filter out invalid values before converting to DATETIME. The naïvequery shown in Listing 2-4 may or may not work on your server.SELECT MessageID ,SenderID ,ReceiverID ,MessageDateAsVarcharColumn ,SomeMoreDataFROM dbo.MessagesWHERE ISDATE(MessageDateAsVarcharColumn) = 1AND CAST(MessageDateAsVarcharColumn AS DATETIME)= '20090707' ;Listing 2-4: An unsafe way to filter out invalid DATETIME values.There is no way to predict whether or not this query will work for you; the databaseengine will evaluate the WHERE conditions in any order it wishes. In fact, if it does workfor you, you are unlucky. If it is going to break, as it inevitably will, it is best to knowimmediately rather than find out later, at some inconvenient moment.61

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

Saved successfully!

Ooh no, something went wrong!