I want to use case statement in where clause but getting error in the query below.
where
(r.WeekId=@WeekId or @WeekId is null) and
(ShiftId=@ShiftId or @ShiftId is null)
and (placeid=@PlaceId or @PlaceId is null)
and (r.StatusId=3)
AND
CASE WHEN @day = 1 THEN ((firstday=@time and (allocateddays is null or NOT (AllocatedDays LIKE '%1%'))))
WHEN @day = 2 THEN ((secondday=@time and (allocateddays is null or NOT (AllocatedDays LIKE '%2%'))))
WHEN @day = 3 THEN ((thirdday=@time and (allocateddays is null or NOT (AllocatedDays LIKE '%3%'))))
ELSE AND (1 = 1)
END
I am getting error at Case statement at line CASE WHEN @day = 1. What is going wrong with my query. Please help.
The
CASEshould be rewritten as anORchain each of which uses@day = nfor one of its conditions, owing to the fact that itCASEis expceted to return a value. It cannot execute conditionally in aWHEREclause.If the condition like
@day = 1returnsTRUE, it is used as a booleanANDwith the rest of the statement. Each of these is chained viaORto the previous.