[英]plsql conditional where clause
I'd like to perform a conditional where
in a sql statement, and use two different criteria, eg in pseudo code: 我想执行的条件where
在一个SQL语句,使用两个不同的标准,例如在伪代码:
procedure(..., bool_value IN boolean default false) is
....
begin
select * from mytable mt
where
if bool_value = true then mt.criterion_1 = value
else
mt_.criterion_2 = value; -- if boolean value is set, use criterion_1 column, otherwise use criterion_2 column
end
Suppose it's possible, What's the best way to do it? 假设它是可能的,最好的方法是什么?
Thanks 谢谢
Try this: 尝试这个:
bool_value_string varchar2(5)
bool_value_string = case when bool_value then 'true' else 'false' end;
select * from mytable mt
where
(bool_value_string = 'true' and mt.criterion_1 = value)
or
(bool_value_string = 'false' and mt.criterion_2 = value)
Basically, convert your when...then idiom to an either...or one. 基本上,将你的...然后成语转换为......或者一个。 Either the boolean field is non-null and true, meaning filter has to be by the first criterion, or it isn't, meaning filter by the second one. 布尔字段是非空和真,意味着过滤器必须是第一个标准,或者它不是,意味着过滤第二个标准。
Basically, your condition gets translated as: 基本上,您的情况被翻译为:
if bool_value = true
then mt.criterion_1 = value
else if bool_value = false
then mt_.criterion_2 = value;
Since you cannot directly use boolean value in select statements (Refer comments), use as below: (Change bool_value from boolean to varchar2 or a number) 由于您无法在select语句中直接使用布尔值(请参阅注释),请使用以下内容:(将bool_value从布尔值更改为varchar2或数字)
procedure(..., bool_value IN varchar2(10) default 'FALSE') is
....
begin
select * from mytable mt
where
(case
when (bool_value = 'TRUE' and mt.criterion_1 = value) then (1)
when (bool_value = 'FALSE' and mt_.criterion_2 = value) then (1)
(else 0)
end) = 1;
OR
select * from mytable mt
where
(bool_value = 'TRUE' and mt.criterion_1 = value)
or
(bool_value = 'FALSE' and mt.criterion_2 = value)
end
ORIGINAL ANSWER 原始答案
You can also use case statement
in where
clause as below: 您还可以在where
子句中使用case statement
,如下所示:
select * from mytable mt
where
(case
when (bool_value = true and mt.criterion_1 = value) then (1)
when (bool_value = false and mt_.criterion_2 = value) then (1)
(else 0)
end) = 1;
In oracle, you can use below Query also. 在oracle中,您也可以使用下面的Query。
select * from mytable mt
where
(bool_value = true and mt.criterion_1 = value)
or
(bool_value = false and mt.criterion_2 = value)
Note: Since default of bool_value = false
, is null
condition need not be checked. 注意:由于bool_value = false
默认值, bool_value = false
无需检查is null
。
Simplest form is this: 最简单的形式是:
WHERE (bool_value = TRUE AND mt.criterion_1 = value)
OR (bool_value = FALSE AND mt.criterion_2 = value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.