dynamic number of where condition in oracle sql

旧街凉风 提交于 2019-12-24 00:38:28

问题


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.


回答1:


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  



回答2:


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)



回答3:


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



回答4:


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

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



来源:https://stackoverflow.com/questions/11553398/dynamic-number-of-where-condition-in-oracle-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!