Archive for October 5th, 2009
Date range with possible NULL values
From Stack Overflow:
Using SQL Server 2008.
I have a stored proc which has start and end date as input parameters for date range.
Looking for a single SQL query which has a
BETWEENpredicate on start and end date in theWHEREclause which can handle both cases where the dates are either bothNULLor both have values.
This can be done by writing an IS NULL check in the expression, like this:
WHERE (@startDate IS NULL OR date >= @startDate) AND (@endDate IS NULL OR date >= @endDate)
or by using a COALESCE on the value of the date itself (so that the range always matches):
WHERE date BETWEEN ISNULL(@startDate, date) AND ISNULL(@endDate, date)
However, none of these conditions uses an index on date efficiently.
Let's create a sample table ans see:
Read the rest of this entry »
Subscribe in a reader