简体   繁体   中英

how to use Case statement in where clause?

I have 6 input fields of which 2 are mandatory. The other 4 fields are optional and are not null values in the tables. I have to pass these 6 values to the cursor query. curor(startdate,enddate,code1,code2,code3,code4) Code1, code2, code3 is the same field name 'X' in the table. how do i include these conditions in the where clause? If code1 is given and others are null the filter condition should include X=code1. Similarly, if code1 and code2 are given then X=code1, code2. if nothing is given then X is all the values rather X filter condition to be eliminated from the query.

select p,q,r from a,b
where a.f1=b.f2
and a.X=code1 <<if only code1 is passed>>
and a.X in (code1,code2)  <<if both code1 and code2 are passed>>

or 

select p,q,r from a,b
where a.f1=b.f2

<<if no value is passed>>

Please help!

I think you want something like this:

select p, q, r
from a join
     b
     on a.f1 = b.f2
where a.X in (code1, code2) ;

If code2 is NULL , the query will still work. Hence, you can add more codes.

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