I’m creating a query that will be run twice a month:
-
On the 5th of the month looking at billing days 16-last day of the month of the previous month.
datepart(dd,h.BILLED_DATE) > 15 DATEPART(mm, h.billed_date) = DATEPART(mm,dateadd(m,-1,getdate())) and DATEPART(yyyy, h.billed_date) = DATEPART(yyyy,dateadd(m,-1,getdate())) -
On the 20th of the month looking at billing days of 1-15 of the same month.
datepart(dd,h.BILLED_DATE) >= 1 and datepart(dd,h.BILLED_DATE) < 16 and DATEPART(mm, h.BILLED_DATE) = DATEPART(mm,GETDATE()) and DATEPART(yyyy, h.BILLED_DATE) = DATEPART(yyyy,GETDATE()))
These work independently in the where clause. When I try to combine them in a case statement in the where clause, however, I’m getting errors galore, starting with the first inequality after the “then.”
Where
Case
when datepart(dd,getdate()) > 15
then [2 above]
else [1 above]
End
Cure my ignorance.
CASE is an expression that returns a single value. You can’t use it for control of flow like you can in some other languages.
Your query also will not make any usage of indexes on your billed_date column, which you should consider adding to support this query.
How about this re-write, which uses pure datetime operations to build an open-ended range instead of performing all those expensive datepart functions: