1

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 ステートメントでエラーが発生しています CASE WHEN @day = 1。私のクエリで何が問題になっていますか。助けてください。

4

5 に答える 5

3

は、値を返すことが期待されるため、それぞれがその条件の 1 つを使用するチェーンCASEとして書き直す必要があります。句で条件付きで実行することはできません。OR@day = nCASEWHERE

条件が return の場合、ステートメントの残りの部分でブール値として使用され@day = 1ます。これらのそれぞれは、前のものに連鎖しています。TRUEANDOR

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) 
 )
于 2012-11-30T14:53:10.110 に答える
1

コンパイラがそれを処理することはできませんELSE AND...(Fortran などの言語を除く)。

于 2012-11-30T15:40:29.833 に答える
1

WHERE句では、このステートメントは、次のCASEように比較の代替値を指定するためにのみ使用できます。

where @day = 
    case @SomeCondition
        when 1 then @Sunday
        when 2 then @Monday
        ...
    end
于 2012-11-30T14:57:17.433 に答える
0

行:ELSE AND(1 = 1)は非常に疑わしいように見えます。それを取り出して試してみてください。

于 2012-11-30T15:00:01.050 に答える
0

間違っていることの 1 つは、where 句の CASE ステートメントが値を割り当てていることです。たとえば、あなたがするときfirstdaay=@time。そんなことはできません。where 句には、trueorfalseに評価される式のみを入れることができます。その結果、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 ... 
于 2012-11-30T14:55:11.287 に答える