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> TechniquesHow SET LANGUAGE can break a queryJust as the value of ROWCOUNT can be changed at the session level, so can other settings,such as the default language. Many developers test their code only under the defaultlanguage setting of their server, and do not test how their code will respond if executedon a server with a different language setting, or if there is a change in the setting at thesession level.This practice is perfectly correct, as long as our code always runs under the same settingsas those under which we develop and test it. However, if or when the code runs underdifferent settings, this practice will often result in code that is vulnerable to errors,especially when dealing with dates.Consider the case of a stored procedure that is supposed to retrieve from ourObjectsChangeLog table (Listing 1-10) a listing of all changes made to the Objectstable over a given date range. According to the requirements, only the beginning of therange is required; the end of the range is an optional parameter. If an upper bound forthe date range is not provided, we are required to use a date far in the future, December31, 2099, as the end of our range.CREATE PROCEDURE dbo.SelectObjectsChangeLogForDateRange@DateFrom DATETIME ,@DateTo DATETIME = NULLASSET ROWCOUNT 0 ;SELECT ObjectID ,ChangedColumnName ,ChangedAt ,OldValueFROM dbo.ObjectsChangeLogWHERE ChangedAt BETWEEN @DateFromAND COALESCE(@DateTo, '12/31/2099') ;GOListing 1-15: Creating the SelectObjectsChangeLogForDateRangestored procedure.38

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

Saved successfully!

Ooh no, something went wrong!