Using WHERE clause with BETWEEN and null date parameters
How About:
DateCreated BETWEEN COALESCE(@DateFrom, DateCreated) AND COALESCE(@DateTo, DateCreated)
Just need some extra criteria to handle when one or the other is NULL
:
AND (
(DateCreated >= @DateFrom and DateCreated < DATEADD(day,1,@DateTo))
OR (@DateFrom IS NULL AND @DateTo IS NULL)
OR (@DateFrom IS NULL AND DateCreated < DATEADD(day,1,@DateTo))
OR (@DateTo IS NULL AND DateCreated >= @DateFrom)
)
Edit: Giorgi's approach was simpler, here it is adapted for use with DATETIME
:
AND ( (DateCreated >= @DateFrom OR @DateFrom IS NULL)
AND (DateCreated < DATEADD(day,1,@DateTo) OR @DateTo IS NULL)
)
The issue with BETWEEN
or <=
when using a DATE
variable against a DATETIME
field, is that any time after midnight on the last day will be excluded.
'2015-02-11 13:07:56.017'
is greater than '2015-02-11'
Rather than casting your field as DATE
for comparison, it's better for performance to add a day to your variable and change from <=
to <
.
Try this:
WHERE ((DateCreated >= @DateFrom OR @DateFrom IS NULL) AND (DateCreated =< @DateTo OR @DateTo IS NULL))