SQL WHERE depending on day of week

荒凉一梦 提交于 2019-12-22 11:21:29

问题


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

回答1:


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())
)



回答2:


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
   ......


来源:https://stackoverflow.com/questions/40803348/sql-where-depending-on-day-of-week

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!