Oracle递归查询以获取日期范围

时间:2020-04-15 16:06:32

标签: sql oracle date range

我需要使用以下查询来获取日期范围

with DATETABLE (tempdate) AS
( 
SELECT trunc(to_date('2020-01-01 01:00:00','yyyy-mm-dd hh24:mi:ss')) AS tempdate from dual
UNION ALL 
SELECT tempdate + 1 FROM DATETABLE 
where tempdate < to_date('2020-02-01 01:00:00','yyyy-mm-dd hh24:mi:ss')
 )

select tempdate from DATETABLE

我遇到了错误

ORA-01790: expression must have same datatype as corresponding expression
01790. 00000 -  "expression must have same datatype as corresponding expression"
*Cause:    
*Action:
Error at Line: 5 Column: 20

如何解决?

2 个答案:

答案 0 :(得分:0)

在Oracle 18c上,您的查询正常运行,没有错误db<>fiddle

在11g(可能还有其他版本)上,递归查询和日期存在问题,您最好对数字进行递归,然后再将值添加到日期中:

WITH DATETABLE( tempdate ) AS ( 
  SELECT 0
  FROM   DUAL
UNION ALL 
  SELECT tempdate + 1
  FROM   DATETABLE 
  WHERE  DATE '2020-01-01' + tempdate + 1 <= DATE '2020-02-01'
)
SELECT DATE '2020-01-01' + tempdate AS tempdate
FROM   DATETABLE

Results

|             TEMPDATE |
|----------------------|
| 2020-01-01T00:00:00Z |
| 2020-01-02T00:00:00Z |
| 2020-01-03T00:00:00Z |
  ...
| 2020-01-30T00:00:00Z |
| 2020-01-31T00:00:00Z |
| 2020-02-01T00:00:00Z |

答案 1 :(得分:0)

这将适用于11g及更高版本的所有版本:

with t AS
( 
  SELECT DATE '2020-01-01' + level -1 AS tempdate from dual
  CONNECT BY LEVEL <= DATE '2020-02-01' - DATE '2020-01-01'
 )
SELECT tempdate FROM t;

输出:

TEMPDATE
--------
01-01-20
02-01-20
03-01-20
04-01-20
05-01-20
06-01-20
07-01-20
08-01-20
09-01-20
10-01-20
11-01-20
12-01-20
13-01-20
14-01-20
15-01-20
16-01-20
17-01-20
18-01-20
19-01-20
20-01-20
21-01-20
22-01-20
23-01-20
24-01-20
25-01-20
26-01-20
27-01-20
28-01-20
29-01-20
30-01-20
31-01-20

31 rows selected.