如何获得月中的所有日子?

时间:2014-10-08 18:06:44

标签: sql oracle

可以将Oracle SQL / PLSQL中的所有日期都作为表格获取吗?

从bla-bla-bla DUAL中选择*

结果:

1 rec: 01.01.2012
2 rec: 02.01.2012
3 rec: 03.01.2012
...
4 rec: 31.01.2012

2 个答案:

答案 0 :(得分:5)

这就是你要找的东西;

select to_date('01.01.2012','dd.mm.yyyy')+level-1
 from dual 
 connect by level <= TO_CHAR(LAST_DAY(to_date('01.01.2012','dd.mm.yyyy')),'DD')

答案 1 :(得分:1)

ADD_MONTHS (dt, 1) - dt也是另一种选择。

对于一年中的特定月份,您需要对日期进行硬编码:

WITH d AS
  (SELECT TRUNC ( to_date('01.01.2012','dd.mm.yyyy'), 'MM' ) - 1 AS dt
  FROM dual
  )
SELECT dt + LEVEL 
   FROM d 
  CONNECT BY LEVEL <= ADD_MONTHS (dt, 1) - dt
/

否则,要获取当月的列表,只需使用SYSDATE而不是硬编码日期:

SQL> WITH d AS
  2    (SELECT TRUNC(sysdate,'MM') -1 AS dt FROM dual
  3    )
  4  SELECT dt + LEVEL
  5     FROM d
  6    CONNECT BY LEVEL <= ADD_MONTHS (dt, 1) - dt
  7  /

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

31 rows selected.

SQL>