简体   繁体   中英

Using case expression inside where clause

what I wanted is to add another condition using case statement or something.

I tried:

SELECT * FROM tblcust 
WHERE cust_id = :p_cust_id 
CASE WHEN :p_first_name IS NOT NULL THEN
        AND first_name = :p_first_name
     WHEN :p_last_name IS NOT NULL THEN
        AND last_name = :p_last_name
     WHEN :p_first_name IS NULL AND :p_last_name IS NULL THEN
        NULL
     END;

You may not be able to use a CASE expression here to represent your logic, but it can certainly be reworded:

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));

But this is ugly, and we might able to use a COALESCE trick here to make it simpler:

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));

The reason your CASE expression is structured incorrectly is because you are making it generate logical expressions , when it is only allowed to generate values . But, in this case, we don't even need a CASE expression to handle your logic.

I am not sure what you want logically , but you can do case inside a case like

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

To make theses "mutually exclusive" sets of conditons use parentheses plus 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)

If there are still more conditions to add the be careful to contain all the sets within an "catch all" pair of parentheses

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM