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.
DATE, thenWHERE DateCreated >= COALESCE(@DateTo, '19000101') AND DateCreated <= COALESCE(@DateFrom, CONVERT(DATE, GETDATE()));- if either of them areDATETIME, you need to stop thinking about "between"...BETWEENcauses more problems with ambiguity than it solves by shortening a predicate slightly.COALESCEorCONVERTfunctions. The code is justCOALESCE(@DateFrom, CONVERT(DATE, GETDATE()))- Both the parameter@DateFromand the system functionGETDATE()are runtime constants, thereforeCOALESCEandCONVERTwill only be evaluated once.