Oracle选择具有动态表名的查询

时间:2014-03-21 22:01:08

标签: sql oracle

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

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

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

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

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

1 个答案:

答案 0 :(得分:2)

您可以为主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语句形式未考虑NULLstart_date的{​​{1}}值。

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

相关问题