Isnull - where子句的案例和条件

时间:2018-04-02 18:02:32

标签: sql-server

我有一段代码片段,其中有一堆'其中'条件与'和'合并条款。我想做以下操作:

...     
     and admission_date > release_date
     and case when @sample = 'typeA'
            then 
            (
            (isnull(@toll_id, 0) > 0 and exists(select fk_id from dbo.tollitem where toll_id = @toll_id and isdel=0))
            or 
            (isnull(@toll_id, 0) = 0)
            )

所以我有一个@Sample参数,它有两个值 - Type A或Type B.我想只在@sample = typeA时检查where子句的条件。 上面是我的代码,我得到错误的语法错误。有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

这不是CASE表达式的工作原理。在WHERE子句中,您仍然需要创建一个布尔表达式。因此:

WHERE CASE WHEN Col1 = 1 THEN Col2 = 2 OR Col3 = 3 ELSE Col4 = 1 END;

完全错误,CASE只完成表达式的一侧,并且还试图评估WHEN内的布尔表达式。 WHEN返回一个值,而不是布尔值。正确使用CASE将与上述示例无关:

WHERE CASE TransactionType WHEN 'Transfered' THEN 'New Business'
                           WHEN 'Adjustment' THEN 'Endorsement'
                           ELSE TransactionType END = @Trantype;

在黑暗中这是一个镜头,但我认为你所追求的是:

AND admission_date > release_date
AND (@sample = 'typeA'
AND  ((isnull(@toll_id, 0) > 0 AND EXISTS(SELECT fk_id
                                          FROM dbo.tollitem
                                          WHERE toll_id = @toll_id
                                            AND isdel=0))
 OR  (isnull(@toll_id, 0) = 0)))

答案 1 :(得分:1)

你绝对应该把它重写为:

and admission_date > release_date
     and  
       (@sample = 'typeA' and
            (((isnull(@toll_id, 0) > 0 and exists(select fk_id from dbo.tollitem where toll_id = @toll_id and isdel=0))
            or 
            (isnull(@toll_id, 0) = 0)
            )))