【问题标题】:Oracle Select query with dynamic table name具有动态表名的 Oracle Select 查询
【发布时间】:2014-03-21 22:01:08
【问题描述】:

我正在尝试创建一个复杂的选择查询,它使用如下临时表和语法

with as
  table1
    (   select start_date, end_date ....somequery - returns only 1 row ),
  table2
    ( select ... somequery use table1 columns in where clause.. ),
  table3
    ( select ... use table1 columns in where clause .. )
select * from 
                select case when  ( start_date < sysdate -1000 and end_date > sysdate ) then 'table2' else 'table3' end  from table1 
         where rownum < 10

所以逻辑很简单,基于表 1 的返回值,我可能想查询表 2 或可能想查询表 3

问题:Oracle不允许在sql查询中动态生成表名

我知道我可以编写一个程序并使用 EXECUTE IMMEDIATE,但由于某种原因,我必须通过单个查询来完成所有事情。任何帮助将不胜感激。

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    你可以为你的主要select做这样的事情:

    select *
    from table1 cross join
         table2
    where start_date < sysdate - 1000 and end_date > sysdate and rownum < 10
    union all
    select *
    from table1 cross join
         table3
    where not (start_date < sysdate - 1000 and end_date > sysdate) and rownum < 10
    

    我们的想法是使用union all 作为这两个条件,where 保证根据您的条件不返回任何行。请注意,where 语句的这种形式不考虑 start_dateend_dateNULL 值。

    如果有更多关于 table2 和 table3` 的详细信息,我怀疑可能还有另一种方法来编写此查询。

    【讨论】:

    • 感谢您的回复。两个表都有 100,000 行作为输出,但对于 table2,查询是在较小的数据表集上进行的,例如1,000,000 但 table3 使用大量聚合函数查询了大约 10,000,000 个。表 3 包含来自表的查询,这些表纯粹类似于日志表,这些表具有对应于表 2 查询中使用的主表的任何条目的变量命中。如果用户想要完整报告,这就是我们更喜欢使用表 2 的原因,否则我们别无选择,只能转到表 3(查询需要 3-4 分钟才能出来。)我会尝试您的解决方案,看看是否有帮助。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 2020-02-25
    • 1970-01-01
    • 2021-03-21
    相关资源
    最近更新 更多