简体   繁体   English

如何在where子句中使用Case语句?

[英]how to use Case statement in where clause?

I have 6 input fields of which 2 are mandatory. 我有6个输入字段,其中2个是必填字段。 The other 4 fields are optional and are not null values in the tables. 其他4个字段是可选的,并且在表中不是空值。 I have to pass these 6 values to the cursor query. 我必须将这6个值传递给游标查询。 curor(startdate,enddate,code1,code2,code3,code4) Code1, code2, code3 is the same field name 'X' in the table. curor(开始日期,结束日期,代码1,代码2,代码3,代码4)代码1,代码2,代码3与表中的字段名称“ X”相同。 how do i include these conditions in the where clause? 我如何在where子句中包含这些条件? If code1 is given and others are null the filter condition should include X=code1. 如果给定code1且其他为null,则过滤条件应包括X = code1。 Similarly, if code1 and code2 are given then X=code1, code2. 同样,如果给定code1和code2,则X = code1,code2。 if nothing is given then X is all the values rather X filter condition to be eliminated from the query. 如果未给出任何内容,则X是所有值,而不是要从查询中消除的X过滤条件。

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. 如果code2NULL ,查询将仍然有效。 Hence, you can add more codes. 因此,您可以添加更多代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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