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