我想在where子句中使用case语句,但在下面的查询中收到错误。
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
我在第CASE WHEN @day = 1
行的Case语句中收到错误。我的查询出了什么问题。请帮忙。
答案 0 :(得分:3)
CASE
应该被重写为OR
链,每个链都使用@day = n
作为其中一个条件,因为它CASE
已被指示返回一个值。它不能在WHERE
子句中有条件地执行。
如果@day = 1
之类的条件返回TRUE
,则它将作为布尔AND
与语句的其余部分一起使用。其中每个都通过OR
链接到上一个。
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)
/* I *think* I have the () groups correct here... There's an unnecessary double (()) around firstday|secondday|thirddad */
AND (
(@day = 1 AND ((firstday=@time and (allocateddays is null or NOT (AllocatedDays LIKE '%1%')))))
OR (@day = 2 AND ((secondday=@time and (allocateddays is null or NOT (AllocatedDays LIKE '%2%')))))
OR (@day = 3 AND ((thirdday=@time and (allocateddays is null or NOT (AllocatedDays LIKE '%3%')))))
/* Not certain if this is necessary in your case, as a catch-all to replace your ELSE */
OR (@day NOT IN (1,2,3) AND 1=1)
)
答案 1 :(得分:1)
在WHERE
子句中,CASE
语句只能用于为比较指定替代值,如下所示:
where @day =
case @SomeCondition
when 1 then @Sunday
when 2 then @Monday
...
end
答案 2 :(得分:1)
你不能让ELSE AND...
没有编译器会处理它(除了像Fortran这样的语言)。
答案 3 :(得分:0)
有一件事是错误的,即where子句中的CASE语句是赋值。例如,当您执行firstdaay=@time
时。你不能这样做。您只能将表达式放在评估为true
或false
的where子句中,仅此而已。因此,你的整个where子句是错误的,坦率地说,对我来说没有多大意义。
where
子句中的那些条件似乎更多地属于select
子句:
select ...
case when @day=1 and (allocateddays is null or NOT (AllocatedDays LIKE '%1%') then firstday=@time else null end as first_day,
case when @day=2 and (allocateddays is null or NOT (AllocatedDays LIKE '%2%') then secondday=@time else null end as second_day
from ...
答案 4 :(得分:0)
该行: ELSE和(1 = 1) 看起来很可疑。 拿出来尝试。