Requirement: select by date as After, Before, Between or all if null
I’m using SQL Server 2008
This is my attempt but I’m getting syntax errors on code that is valid used outside of the case.
- Is there a better method?
-
using case what is the correct syntax?
declare @StartDate datetime; declare @EndDate datetime; SET @EndDate = GETDATE(); SET @StartDate = DATEADD(year, -2, GETDATE()); select * from ArCustomer where CAST(Customer as int) > 1000 AND CASE WHEN @StartDate IS NOT NULL AND @EndDate IS NOT NULL THEN ArCustomer.DateLastSale BETWEEN @StartDate AND @EndDate WHEN @StartDate IS NULL AND @EndDate IS NOT NULL THEN ArCustomer.DateLastSale < @EndDate WHEN @StartDate IS NOT NULL AND @EndDate IS NULL THEN ArCustomer.DateLastSale > @StartDate END;
Alternately, you could not restrict by the date parameter if it is
NULL:Or… you can handle the
NULLby treating it as the low-end or high-end date:EDIT:
There could be a difference in the execution plan between these two approaches, so you might try both methods and see if one out-performs the other…