One of my WHERE
clauses is the following:
AND (DateCreated BETWEEN @DateFrom and @DateTo OR (@DateFrom IS NULL OR @DateTo IS NULL))
@DateFrom
and @DateTo
are input parameters that may be NULL
.
If they are both null, then I need to basically ignore the BETWEEN
and return all records.
If @DateFrom
is NULL
, but @DateTo
is NOT NULL
, then I need to return all records with DateCreated being no greater than @DateTo
(inclusive).
If @DateFrom
is NOT NULL
, but @DateTo
is NULL
, then I need to return all records with DateCreated being no earlier than @DateFrom
(inclusive) up to today's date.
DateCreated is not a null or some time it is null field.
So far my WHERE
clause is not working exactly like I want.
Null values can be used as a condition in the WHERE and HAVING clauses. For example, a WHERE clause can specify a column that, for some rows, contains a null value.
The SQL BETWEEN OperatorThe values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.
Note: DATEADD and DATEDIFF SQL function can be used in the SELECT, WHERE, HAVING, GROUP BY and ORDER BY clauses.
"NULL" can be specified as a value in the Date field to get an empty/blank by using INSERT statement. Example: CREATE table test1 (col1 date); INSERT into test1 values (NULL);
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With