简体   繁体   中英

How to use IF THEN ELSE statement in where clause in Oracle?

I'm interesting that how can I use if-then-else statement or any control structure in where clause in Oracle. I want to use as:

  • when pcustomer_id IS NULL then WHERE c.customer_id IS NULL
  • and when pcustomer_id IS NOT NULL then c.customer_id = pcustomer_id .

How can I do it?

SELECT *
  FROM customer_inf c
 WHERE 
IF
 pcustomer_id IS NULL THEN ( c.customer_id IS NULL ) 
    ELSE (c.customer_id = pcustomer_id) END IF;

You need to bundle them

where (
(pcustomer_id is null 
    and c.customer_id is null)
or 
(pcustomer_id is not null 
    and c.customer_id = pcustomer_id)
)

Use boolean expressions:

SELECT *
FROM   customer_inf c
WHERE  ( pcustomer_id IS NULL AND c.customer_id IS NULL )
OR     ( pcustomer_id IS NOT NULL AND cc.customer_id = pcustomer_id);

If I understand correctly you just want to return all values when c.customer_id = pcustomer_id including null equity. So:

select * from customer_inf c 
where nvl(pcustomer_id,'999999999999') = nvl(c.customer_id, '999999999999');

You just need to select number that cannot occur in your real data.

WHERE NVL(pcustomer_id,c.customer_id) IS NULL OR NVL2(pcustomer_id,c.customer_id,pcustomer_id)=pcustomer_id

说明:此处,在第一个NVL中,如果pcustomer_id为null,则传递c.customer_id,如果第二个NVL2 1中的pcustomer_id不为null,则将检查Null,然后c.customer_id = pcustomer_id

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