Write a function that takes a date and calculates the time from the end of the year

--Write a function, input a date, calculate its time from the end of the year
create or replace function f_end(i_date varchar2)
return number
is
/*declare four variables, v_end: store the date of the end of the input date
v_date: store the converted into Date-type input string
v_minus: store the difference between two dates
v_errm: store exception */

v_end date;
v_date date;
v_minus number;
v_errm varchar2(50);
begin
 /* Function analysis: length: calculate the length of the string;
 to_date: Convert character type to date type;
 trunc: truncation function, 'yyyy': truncate by year, return the first day of January of the current year,
 'mm': truncate by month, return the first day of the current month,
 'dd': truncate by day, return 12 o'clock in the morning of the day;
 add_months: month addition and subtraction, + for addition, - for subtraction;
 last_day: return the last day of the month*/

  if length(i_date)<>8 then
    dbms_output.put_line('The input date format is incorrect, correct The format is: yyyymmdd');
  end if;
  v_date:=to_date(i_date,'yyyymmdd');
  v_end:=last_day(add_months(trunc(v_date,'yyyy'),11));
  v_minus:=v_end-v_date;
  return v_minus;
  --异常处理
  exception
    when others then
      v_errm:=sqlerrm;
      dbms_output.put_line(v_errm);
end f_end;
--调用函数
select f_end('20230330') from dual;

 Note: The difference between a function and a stored procedure is that the function has a return value, and there is only one return value.

Guess you like

Origin blog.csdn.net/lxslf/article/details/129861417