【问题标题】:How to populate calendar table in Oracle?如何在 Oracle 中填充日历表?
【发布时间】:2012-01-12 13:58:19
【问题描述】:

我想在 Oracle DB 中维护一个日历表,我想用从 2011 年到 2013 年(可能到任何一年)的一年中的所有日子来填充它。我该怎么做?

考虑我的数据库表有列,示例数据集是:

S.No  Cal_Dt      DayName 
1     01-01-2011  Monday
2     02-01-2011  Tuesday
3     03-01-2011  Wednesday

等等。

我只在这里更关心 Cal_Dt(DayName 是可选的)。

【问题讨论】:

    标签: sql database oracle


    【解决方案1】:
    declare
      v_date date := to_date('20110101','yyyymmdd');
    begin
    
       while v_date < sysdate + 720 loop
    
          insert into calender
          values ( v_date, to_char(v_date,'DAY'));
    
          v_date := v_date + 1;
    
       end loop;
       commit;
    
    end;
    /
    

    这不是最佳做法,您应该使用Allesandro Rossi's solution。这可能在您使用 Oracle 9i 或更早版本并填充大表时有用。

    【讨论】:

    • 如果我想从一年中的第一天开始,并想进一步进行而不是从 sysdate 开始?
    • @太棒了,我已经编辑了它,所以你可以在任何你想要的地方开始它。
    【解决方案2】:

    这是一种简单易行的方法

    with calendar as (
            select :startdate + rownum - 1 as day
            from dual
            connect by rownum < :enddate - :startdate
        )
    select rownum as "S.No", to_date(day,'dd_mm_yyyy') as "Cal_Dt", to_char(day,'day') as "DayName"
    from calendar
    

    【讨论】:

    • 在 Oracle 11g 中运行查询时,我收到错误 ORA-00904:"STARTDATE":invalid identifier。给定的输入日期格式为 01012016。请帮忙。
    • 您必须将 :startdate 和 :enddate 替换为对您的特定情况有意义的值。
    【解决方案3】:
    with calendar as (
            select rownum - 1 as daynum
            from dual
            connect by rownum < sysdate - to_date('1-jan-2010') + 1
        )
    select to_date('1-jan-2010') + daynum as monthdate
    from calendar
    ;
    

    【讨论】:

      猜你喜欢
      • 2011-01-03
      • 2018-11-25
      • 2011-05-15
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多