开发者

PL/SQL and date intervals

开发者 https://www.devze.com 2023-01-23 11:22 出处:网络
I have a date and I\'d like to print the offset from that date. 开发者_StackOverflowI can do this:

I have a date and I'd like to print the offset from that date. 开发者_StackOverflowI can do this:

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

and it works fine. The problem is that the interval is variable. When I try this:

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

I get a compiler error.

I thought it might be because g_dateOffsetAmt is an integer so I tried this:

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

Though I still get compiler errors saying:


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

Is there some other way to do this?


You would probably want to use the NumToYMInterval function

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


There are a couple ways to do this.. Either type your variable being passed in as an interval, or use the function add_months instead:

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; 
0

精彩评论

暂无评论...
验证码 换一张
取 消