【问题标题】:dynamic number of where condition in oracle sqloracle sql中where条件的动态数量
【发布时间】:2012-07-19 03:11:45
【问题描述】:

我需要为报表工具中的提示编写 sql。我得到了一个变量中的多个值的列表,用'-'分隔,这些值的数量可能会有所不同。(eg1."abc-def" eg2."abc-def-xyz")。

现在我需要用这种形式的oracle写sql(逻辑上)

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 '-'.

我不能使用 plsql 进行查询。要么我可能不知道使用我在 plsql 中选择的变量,要么可能是报告工具不支持。

提前致谢。

【问题讨论】:

    标签: sql oracle dynamic


    【解决方案1】:

    试试

    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);
    

    概括(考虑到您的字段用“-”分隔)

    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);
    

    基本上子查询的输出如下图——

      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】:

      首先使用 Oracle 的 regexp_substr() 函数将字符串拆分为多个部分。请参阅regexp_substr function(如果您可以访问生成字符串的原始文件,请使用它。)

      其次,把它放在一个临时表中,然后就可以了:

      select something
        from somewhere
       where someColumn in (select parts from tmpTable)
      

      【讨论】:

      • 不需要临时表,内联视图就足够了。此外,在报告工具中使用 PLSQL 存储过程(无论如何都可以完成)填充临时表(使用用户输入)似乎是不必要的。
      • @Annjawn,我同意你关于临时表的观点,但他对这个太陌生了,我想让它尽可能简单和可测试。
      【解决方案3】:
      select something
        from somewhere
       where INSTR('-'||'abc-def-ghi'||'-', '-'||someColumn||'-') > 0;
      

      【讨论】:

        【解决方案4】:

        如果你只想要一个包含'-'的结果列表,你可以这样做

        从某处某处选择某物,例如('%-%');

        【讨论】:

        • 我已经编辑了这个问题。你介意看一下吗?
        猜你喜欢
        • 2020-10-13
        • 2014-09-30
        • 1970-01-01
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 2013-10-06
        • 1970-01-01
        相关资源
        最近更新 更多