给出ORA-01790的递归SQL

使用Oracle 11g第2版,以下查询给出了ORA-01790:表达式必须与相应的表达式具有相同的数据类型:

with intervals(time_interval) AS
 (select trunc(systimestamp)
    from dual
  union all
  select (time_interval + numtodsinterval(10, 'Minute'))
    from intervals
   where time_interval < systimestamp)
select time_interval from intervals;

该错误表明UNION ALL的两个子查询的数据类型都返回不同的数据类型.

即使我在每个子查询中转换为TIMESTAMP,我也会得到相同的错误.

我错过了什么?

编辑:我不是在寻找CONNECT BY替代品.

最佳答案
在我看来,对于带有日期或时间戳列的查询,“递归子查询因子”在11g R2中被打破.

with test(X) as
(
  select to_date('2010-01-01','YYYY-MM-DD') from dual
  union all (
    select (X + 1) from test where X <= to_date('2010-01-10','YYYY-MM-DD') 
  )
)
select * from test;

ORA-01790

使用强制转换来转换数据类型:

with test(X) as
(
  select cast(to_date('2010-01-01','YYYY-MM-DD') as date) from dual
  union all (
    select (X + 1) from test where X <= to_date('2010-01-10','YYYY-MM-DD') 
  )
)
select * from test;

X
-------------------
2010-01-01 00:00:00

1 row selected

将日期投射到日期是有帮助的,但其他结果在哪里?

它变得更好……

尝试使用另一个开始日期:

with test(X) as
(
  select cast(to_date('2007-01-01','YYYY-MM-DD') as DATE) from dual
  union all (
    select (X + 1) from test where X <= to_date('2011-01-11','YYYY-MM-DD') 
  )
)
select * from test 
where rownum < 10; -- important!

X
-------------------
2007-01-01 00:00:00
2006-12-31 00:00:00
2006-12-30 00:00:00
2006-12-29 00:00:00
2006-12-28 00:00:00
2006-12-27 00:00:00
2006-12-26 00:00:00
2006-12-25 00:00:00
2006-12-24 00:00:00

9 rows selected

向后倒数?为什么?

更新2014年1月14日:作为一种解决方法,从结束日期开始使用CTE并向后构建递归CTE,如下所示:

with test(X) as
(
  select cast(to_date('2011-01-20','YYYY-MM-DD') as DATE) as x from dual
  union all (
    select cast(X - 1 AS DATE) from test 
    where X > to_date('2011-01-01','YYYY-MM-DD') 
  )
)
select * from test 

结果:

|                              X |
|--------------------------------|
| January, 20 2011 00:00:00+0000 |
| January, 19 2011 00:00:00+0000 |
| January, 18 2011 00:00:00+0000 |
| January, 17 2011 00:00:00+0000 |
| January, 16 2011 00:00:00+0000 |
| January, 15 2011 00:00:00+0000 |
| January, 14 2011 00:00:00+0000 |
| January, 13 2011 00:00:00+0000 |
| January, 12 2011 00:00:00+0000 |
| January, 11 2011 00:00:00+0000 |
| January, 10 2011 00:00:00+0000 |
| January, 09 2011 00:00:00+0000 |
| January, 08 2011 00:00:00+0000 |
| January, 07 2011 00:00:00+0000 |
| January, 06 2011 00:00:00+0000 |
| January, 05 2011 00:00:00+0000 |
| January, 04 2011 00:00:00+0000 |
| January, 03 2011 00:00:00+0000 |
| January, 02 2011 00:00:00+0000 |
| January, 01 2011 00:00:00+0000 |

测试进行:

Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production

转载注明原文:给出ORA-01790的递归SQL - 代码日志