代码之家  ›  专栏  ›  技术社区  ›  FrustratedWithFormsDesigner

PL/SQL和日期间隔

  •  2
  • FrustratedWithFormsDesigner  · 技术社区  · 14 年前

    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_dateOffsetAmt 是一个 integer

    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 回复  |  直到 14 年前
        1
  •  3
  •   Craig    14 年前

    有两种方法可以做到。。请键入作为间隔传入的变量,或改用函数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; 
    
        2
  •  6
  •   Justin Cave    14 年前

    您可能想使用numtoymenterval函数

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