3

I have a requirement to check records up to differing dates, depending on which day of the week it is currently.

On a Friday I need for it to look at the entire next week, until Sunday after next. On any other day it should check the current week, up until the coming Sunday.

I have the below currently but it's not working due to syntax error. Is it possible to do a CASE WHEN inside a WHERE clause?

WHERE
    T0.[Status] IN ('R','P') 
    AND
        CASE 
           WHEN DATEPART(weekday,GETDATE()) = '5' 
              THEN T0.[DueDate] >= GETDATE() AND <= DATEADD(day, 15 - DATEPART(weekday, GetDate()), GetDate())
           WHEN DATEPART(weekday, GETDATE()) != '5' 
              THEN T0.[DueDate] >= GETDATE() AND <= DATEADD(DAY ,8- DATEPART(weekday, GETDATE()), GETDATE())
        END
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
coblenski
  • 1,119
  • 2
  • 11
  • 19
  • 1
    Yes, it is possible - but it's generally a bad idea. Use AND/OR instead. – jarlh Nov 25 '16 at 10:57
  • 1
    Are you absolutely sure you phrased your requirements correctly? Note that they mean that on Friday, you need to look nine days ahead, but on Saturday, only one. If instead, on Saturday, you need to look eight days ahead, you can simply your logic: look up to the next Friday, plus two additional days. –  Nov 25 '16 at 11:19
  • Yeah, hvd. It seems wrong but that's how it was described to me. I guess the idea is that it won't be checked on the weekend anyway so that's okay. However I see your point and that would probably be much simpler now that I think about it. – coblenski Nov 25 '16 at 11:30

2 Answers2

4

It's much easier to create this logic with a series of logical or and and operators:

WHERE
T0.[Status] IN ('R','P') AND
((DATEPART(weekday,GETDATE()) = '5' AND 
  T0.[DueDate] >= GETDATE() AND 
  T0.[DueDate] <= DATEADD(day, 15 - DATEPART(weekday, GetDate()), GetDate())) OR
 (DATEPART(weekday,GETDATE()) != '5' AND 
  T0.[DueDate] >= GETDATE() AND 
  T0.[DueDate] <= DATEADD(DAY ,8- DATEPART(weekday,GETDATE()),GETDATE())
)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Your syntax is wrong, you are using a condition evaluation in the THEN clause instead of an assignemnet

  WHEN DATEPART(weekday,GETDATE()) = '5' THEN  Your_column1  ELSE your_column2 END
  ......

or a inner case

  CASE
    WHEN DATEPART(weekday,GETDATE()) = '5' THEN 
            CASE  WHEN T0.[DueDate] >= GETDATE() 
                    AND <= DATEADD(day, 15 - DATEPART(weekday, GetDate()), GetDate())  
                    THEN Your_column1  ELSE your_column2 
            END 
 END
   ......
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107