简体   繁体   中英

dynamic number of where condition in oracle sql

I need to write a sql for a prompt in a reporting tool. I get the list of multiple values in a variable separated by '-' and the number of such values can vary.(eg1."abc-def" eg2."abc-def-xyz").

Now I need to write sql in oracle of this form(logically)

select something
  from somewhere
 where someColumn in 'abc' -- use substr to extract abc
    or someColumn in 'def' -- use substr to extract def
    or ...till we don't find '-'.

I can't use plsql for the query. Either I may not be knowing to use the variable in which I select into in plsql or may be the reporting tool doesn't support that.

Thanks in advance.

Try

select something
  from somewhere
 where someColumn in (select regexp_substr('abc-def-xyz','[^-]+', 1, level) from dual
                     connect by regexp_substr('abc-def-xyz', '[^-]+', 1, level) is not null);

To generalize (considering your fields are separated by "-")

select something
  from somewhere
 where someColumn in (select regexp_substr(variable,'[^-]+', 1, level) from dual
                     connect by regexp_substr(variable, '[^-]+', 1, level) is not null);

Basically the output of the subquery is shown below -

  SQL> select regexp_substr('abc-def-xyz','[^-]+', 1, level) value from dual
      connect by regexp_substr('abc-def-xyz', '[^-]+', 1, level) is not null;

VALUE                            
-------------------------------- 
abc                              
def                              
xyz  

First split the string into its parts using Oracle's regexp_substr() function. See regexp_substr function (If you can access the original that generates the string, just use that.)

Second, put this in a temp table and then just have:

select something
  from somewhere
 where someColumn in (select parts from tmpTable)
select something
  from somewhere
 where INSTR('-'||'abc-def-ghi'||'-', '-'||someColumn||'-') > 0;

If you just want a list of results that contain a '-', you could just do something like

SELECT SOMETHING FROM SOMEWHERE WHERE SOMECOLUMN LIKE ('%-%');

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