簡體   English   中英

WHERE子句中的SQL查詢錯誤CASE語句

[英]SQL query error CASE statement in WHERE clause

我需要在具有CASE表達式的存儲過程中具有WHERE條件。 我嘗試了以下操作,但是在第三行的=符號處出現錯誤。 請,有人可以糾正我/為我指出類似情況的例子嗎?

WHERE CASE WHEN @Param1 IS null THEN (
  (@Param1 = '(All)')
  OR (@Param1 = '(Ready)' AND t.Column1 NOT IN ('Descoped','Done'))
  OR (@Param1 = '(Pending)' AND t.Column1 NOT IN ('Descoped','Done')
    AND t.Column2 IN ('Deferred','Rejected','Ready for Test'))
  OR (@Param1 = t.Column1 )
ELSE (
  t.Column1 = 'WIP'
  OR t.Column1 ='Not Started'
) END

該查詢僅用於表示。 我正在使用MS SQL 2008 R2。

在大多數SQL方言(包括SQL Server)中,不能將條件置於case內。 通常,如果您根本在where子句中使用case ,那么您將尋求較差的解決方案。 正確的方法是使用布爾邏輯重寫整個過程:

WHERE  ( @Param1 IS NOT NULL 
         AND ( @Param1 IN ( '(All)', t.column1 ) 
                OR ( @Param1 = '(Ready)' 
                     AND t.column1 NOT IN ( 'Descoped', 'Done' ) ) 
                OR ( @Param1 = '(Pending)' 
                     AND t.column1 NOT IN ( 'Descoped', 'Done' ) 
                     AND t.column2 IN ( 'Deferred', 'Rejected', 'Ready for Test' ) ) ) ) 
        OR ( @Param1 IS NULL 
             AND t.column1 IN ( 'WIP', 'Not Started' ) ) 

為此,檢查@Param1是否不為null是毫無意義的。 由於null = anything始終為false,因此查詢的前半部分中的所有條件在@Param1為null時都將返回false。 這應該可以更直接地完成您要嘗試的工作:

WHERE  @Param1 IN ( '(All)', t.column1 ) 
        OR ( @Param1 = '(Ready)' 
             AND t.column1 NOT IN ( 'Descoped', 'Done' ) ) 
        OR ( @Param1 = '(Pending)' 
             AND t.column1 NOT IN ( 'Descoped', 'Done' ) 
             AND t.column2 IN ( 'Deferred', 'Rejected', 'Ready for Test' ) ) 
        OR ( @Param1 IS NULL 
             AND t.column1 IN ( 'WIP', 'Not Started' ) ) 

SQL中的大小寫返回一個值。 這不是控制流程。 如果您需要根據變量匹配不同的條件,則可能應編寫如下內容

select * from myTable t
where t.id =
case when @Param1 is null then
    2
else
    1
End

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM