Oracle - 无法创建日期引用表

时间:2016-10-04 20:43:35

标签: oracle plsql

我正在尝试使用日期键创建一个引用表,显示所有日期以及我的表中的引用。但是,这并不像我期望的那样有效。

DECLARE
  start_date DATE := TO_DATE('2009-01-01','YYYY-RR-DD');
  end_date DATE := TO_DATE('2021-01-01','YYYY-RR-DD');
BEGIN
  WHILE start_date < end_date LOOP
      SELECT 
            TO_CHAR(start_date, '-YYYYMMDD') AS DATE_KEY
          , TO_CHAR(start_date, 'YYYY-MM-DD') AS "ACTUAL_DATE"
          , EXTRACT(YEAR FROM start_date) AS "YEAR"
          , EXTRACT(MONTH FROM start_date) AS "MONTH"
          , TO_CHAR(start_date, 'MONTH') AS "MONTH_NAME"
          , TO_CHAR(start_date, 'WW') AS "WEEK_OF_YEAR"
          , EXTRACT(DAY FROM start_date) AS "DAY"
          , TO_CHAR(start_date, 'DDD') AS "DAY_OF_YEAR"
          , TO_CHAR(start_date, 'DAY') AS "WEEKDAY"
          , TO_CHAR(start_date, 'Q') AS "QTR_OF_YEAR"
          , TO_CHAR(start_date, 'MONTH DD, YYYY') AS FRIENDLY
      INTO V_DATE
      FROM dual;
      start_date := start_date+1;
  END LOOP;
END;

我收到此错误,但无论我尝试什么,我都会遇到错误。 我已经尝试声明V_DATE,但这没有正常工作。

作为解决方法,我能够在Excel中创建所需的表,但它有一个小问题 一周的一周。我可以在加载此数据后使用更新查询来解决此问题。 拥有一个将填充的实际查询是理想的,因为这些数据可能会超出我列出的额外年份。

谢谢Allan

2 个答案:

答案 0 :(得分:2)

语法:

select . . .
into v_date
. . .

用于(在Oracle中)选择变量。

您似乎想在表中插入行:

insert into ??( . . . )
    <your select here>;

??是您的表名。 . . .是列的列表。

此外,您可以免除PL / SQL,并通过使用CTE生成所有日期(使用connect by或递归CTE)在单个查询中完成所有操作)。

答案 1 :(得分:0)

您可以使用以下语句创建表:

  CREATE TABLE refdates AS 
  SELECT 
        TO_CHAR(start_date, '-YYYYMMDD') AS DATE_KEY
      , TO_CHAR(start_date, 'YYYY-MM-DD') AS "ACTUAL_DATE"
      , EXTRACT(YEAR FROM start_date) AS "YEAR"
      , EXTRACT(MONTH FROM start_date) AS "MONTH"
      , TO_CHAR(start_date, 'MONTH') AS "MONTH_NAME"
      , TO_CHAR(start_date, 'WW') AS "WEEK_OF_YEAR"
      , EXTRACT(DAY FROM start_date) AS "DAY"
      , TO_CHAR(start_date, 'DDD') AS "DAY_OF_YEAR"
      , TO_CHAR(start_date, 'DAY') AS "WEEKDAY"
      , TO_CHAR(start_date, 'Q') AS "QTR_OF_YEAR"
      , TO_CHAR(start_date, 'MONTH DD, YYYY') AS FRIENDLY
  FROM (SELECT TO_DATE('2008-12-31','YYYY-MM-DD') + level as start_date
        FROM   dual
        CONNECT BY level < 10000);