在Oracle中创建CTE

时间:2016-08-04 18:41:16

标签: sql oracle insert common-table-expression

我正在尝试在CTE中创建一个Oracle,它不会从现有表中进行选择,而是将数据插入其中。目前,我正在创建一个表,然后在query完成后删除它。有没有办法创建一个有效地做同样事情的CTE?这是我目前的代码:

create table RTG_YEARS
(YR date);

insert into RTG_YEARS values (to_date('2013-01-01', 'yyyy-mm-dd'));
insert into RTG_YEARS values (to_date('2013-12-31', 'yyyy-mm-dd'));
insert into RTG_YEARS values (to_date('2014-01-01', 'yyyy-mm-dd'));
insert into RTG_YEARS values (to_date('2014-12-31', 'yyyy-mm-dd'));
insert into RTG_YEARS values (to_date('2015-01-01', 'yyyy-mm-dd'));
insert into RTG_YEARS values (to_date('2015-12-31', 'yyyy-mm-dd'));

1 个答案:

答案 0 :(得分:15)

您可以通过从dual中选择日期值并将它们合并在一起来创建公用表表达式(CTE,subquery factoring等):

with RTG_YEARS (YR) as (
  select to_date('2013-01-01', 'yyyy-mm-dd') from dual
  union all select to_date('2013-12-31', 'yyyy-mm-dd') from dual
  union all select to_date('2014-01-01', 'yyyy-mm-dd') from dual
  union all select to_date('2014-12-31', 'yyyy-mm-dd') from dual
  union all select to_date('2015-01-01', 'yyyy-mm-dd') from dual
  union all select to_date('2015-12-31', 'yyyy-mm-dd') from dual
)
select * from RTG_YEARS;

YR       
----------
2013-01-01
2013-12-31
2014-01-01
2014-12-31
2015-01-01
2015-12-31

与CTE无关,但您可以使用date literals减少输入:

with RTG_YEARS (YR) as (
  select date '2013-01-01' from dual
  union all select date '2013-12-31' from dual
  union all select date '2014-01-01' from dual
  union all select date '2014-12-31' from dual
  union all select date '2015-01-01' from dual
  union all select date '2015-12-31' from dual
)
select * from RTG_YEARS;