I am trying to design a CASE Statement in SQL Server for a report parameter. The report is presenting a timeframe against a set date. The expdate.
The parameter are sent in string format:
'All', '30', '31', '61', '91', '121', '150', '181+'
Trying to develop a CASE
statement that will return:
WHERE expdate
CASE WHEN Timeframe = 'All' Then expdate --All Dates
CASE WHEN timeframe=30 THEN expdate between 0 and 30 --using datediff from today
CASE WHEN timeframe=31 THEN expdate between 31 and 60 --using datediff
CASE WHEN timeframe=61 THEN expdate between 61 and 90 --using datediff
...
If there is a better way to do this than a CASE
statement in the WHERE
clause, I am all ears, but that's how I have done it in the past.
Thanks
I would do it with an (AND) OR (AND) structure, like this:
WHERE (timeframe='All')
OR (timeframe='30' AND expdate between 0 and 30)
OR (timeframe='31' AND expdate between 31 and 60)
OR (...
Not use case when but OR and AND using make condition. I assume that expdate should be stored day. Like this
WHERE (Timeframe = 'All' AND expdate=expdate) --All Dates
OR( timeframe=30 AND expdate between 0 and 30 )--using datediff from today
OR( timeframe=31 AND expdate between 31 and 60 )--using datediff
OR (timeframe=61 AND expdate between 61 and 90) --using datediff
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.