在where子句中使用case表达式

时间:2018-03-21 06:01:00

标签: sql oracle11g

我想要的是使用case语句或其他东西添加另一个条件。

我试过了:

for(int x = lower; x <= upper; x++) {
    decider = true;
    for (int y = 2; y < x; y ++) {   // can probably make this bound even tighter
        if (x % y == 0) {
            decider = false;
            break;
        }
    }
    if (decider)
        primeNumbers.add(x); 
}
return primeNumbers;

3 个答案:

答案 0 :(得分:3)

您可能无法在此处使用CASE表达式来表示您的逻辑,但它当然可以重写:

SELECT * FROM tblcust 
WHERE
    cust_id = :p_cust_id AND
    ((:p_first_name IS NOT NULL AND first_name = :p_first_name) OR
     (:p_last_name IS NOT NULL AND last_name = :p_last_name)    OR
     (:p_first_name IS NULL AND :p_last_name IS NULL));

但这很难看,我们可以在这里使用COALESCE技巧来简化:

SELECT * FROM tblcust 
WHERE
    cust_id = :p_cust_id AND
    (COALESCE(:p_first_name, first_name || ' ') = first_name) OR
     COALESCE(:p_last_name, last_name || ' ') = last_name) OR
     (:p_first_name IS NULL AND :p_last_name IS NULL));

您的CASE表达式结构不正确的原因是,当您只允许生成时,它会生成逻辑表达式。但是,在这种情况下,我们甚至不需要CASE表达式来处理您的逻辑。

答案 1 :(得分:0)

我不确定你想要什么逻辑,但你可以在像

这样的案例中做案例
With a 
as (
Select 1 id , NULL col1 union all
Select 2,10 union all
Select 3,Null
)
Select * from a
where id =1
OR  Case When col1 is not null then id=2
End

答案 2 :(得分:0)

制作论文&#34;互相排斥&#34;条件集使用括号加OR

SELECT * FROM tblcust 
WHERE (:p_first_name IS NOT NULL AND first_name = :p_first_name) 
OR (:p_last_name IS NOT NULL AND last_name = :p_last_name)
OR (:p_FIRST_name IS NULL AND :p_last_name IS NULL AND cust_id = :p_cust_id)

如果还有更多条件要添加,请小心包含&#34;中的所有集合&#34;一对括号