简体   繁体   中英

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:

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)

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:

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.

  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.

Simplest form is this:

WHERE (bool_value = TRUE AND mt.criterion_1 = value)
OR (bool_value = FALSE AND mt.criterion_2 = value)

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