PL / SQL和日期间隔

时间:2010-11-05 14:08:18

标签: oracle plsql intervals

我有一个约会,我想打印那个日期的偏移量。我可以这样做:

dbms_output.put_line(to_char(g_startDate - interval '4' month ,'YYYY-MM-DD'));

它工作正常。问题是间隔是可变的。当我尝试这个时:

dbms_output.put_line(to_char(g_startDate - interval g_dateOffsetAmt month ,'YYYY-MM-DD'));

我收到编译错误。

我认为可能是因为g_dateOffsetAmtinteger所以我试过了这个:

dbms_output.put_line(to_char(g_startDate - interval to_char(g_dateOffsetAmt) month ,'YYYY-MM-DD'));

虽然我仍然遇到编译错误:


Error: PLS-00103: Encountered the symbol "TO_CHAR" when expecting one of the following:

          . ) , * @ & | = - +  at in is mod remainder not rem =>
          ..   or != or ~= >=  and or like
          LIKE2_ LIKE4_ LIKEC_ as between from using || member
           SUBMULTISET_
       The symbol "," was substituted for "TO_CHAR" to continue.
Line: 704

Error: PLS-00103: Encountered the symbol "MONTH" when expecting one of the following:

          . ( ) , * % & | = - +  at in is mod remainder not range
          rem => ..   or != or ~= >=  and or
          like LIKE2_ LIKE4_ LIKEC_ between || multiset member
          SUBMULTISET_
       The symbol "." was substituted for "MONTH" to continue.
Line: 704

还有其他方法吗?

2 个答案:

答案 0 :(得分:6)

您可能想要使用NumToYMInterval函数

declare
  v_interval pls_integer := 4;
begin
  dbms_output.put_line( sysdate - NumToYMInterval( v_interval, 'month' ) );
end;
/

答案 1 :(得分:3)

有几种方法可以做到这一点。要么输入你的变量作为间隔传入,要么使用函数add_months代替:

declare
    v_interval INTERVAL YEAR TO MONTH := interval '4' month;
begin
    dbms_output.put_line(to_char((sysdate - v_interval), 'MM/DD/YYYY'));
end; 

declare
    v_interval PLS_INTEGER := 4;
begin
    dbms_output.put_line(to_char(add_months(sysdate, -v_interval), 'MM/DD/YYYY'));
end;