Reputation: 135
Attempting to query for when, given parameters @startDate and @endDate, a record occurs in as much of the time frame as is supplied. I have a functional where clause below, but I suspect it can be more direct.
If an end date is supplied, records will not be selected from after that date. If a start date is supplied, records will not be selected from before that date. If no dates are supplied all records will be selected.
SELECT *
FROM myTable
WHERE
(
(@startDate IS NULL AND ((@endDate IS NULL) OR (myTable.[recordDate] <= @endDate)))
OR
(@endDate IS NULL AND ((@startDate IS NULL) OR (myTable.[recordDate] >= @startDate)))
OR
(myTable.[recordDate] BETWEEN @startDate AND @endDate)
)
Upvotes: 1
Views: 257
Reputation: 36
Setup a temp tableceiling with floor and ceiling and join to table on date BETWEEN floor and ceiling. Setup your unbounded conditions(NULL)as 1/1/1900 and 12/31/9999. A colleague showed me this recently and it worked.
Upvotes: 0
Reputation: 37023
You could workaround with ISNULL
function like below:
SELECT * FROM myTable
WHERE myTable.[recordDate] >= ISNULL(@startDate, '01/01/1900')
AND myTable.[recordDate] <= ISNULL(@endDate, getDate())
This query will select all the rows that are either:
Upvotes: 1