Given start and end time, calculate the number of weeks across the year (oracle function)

CREATE OR REPLACE FUNCTION get_weekly_times(i_ksrq IN DATE, i_jsrq IN DATE)
  RETURN NUMBER DETERMINISTIC IS

  /**
  * Given the start and end dates, get the number of weeks (supporting cross-years)
  * Every week: Monday to Sunday
  *
  * Add determninistic to the function. During SQL execution, for the same input parameters, the function returns the same value, db Will automatically cache it for us.
  * 
  */

  v_dsdez_zr DATE; --Sunday of the penultimate week
  v_zs NUMBER; --Week number

  v_ksrq DATE DEFAULT trunc(i_ksrq); --Remove hours, minutes and seconds
  v_jsrq DATE DEFAULT trunc(i_jsrq); --Remove hours, minutes and seconds
BEGIN
  v_dsdez_zr := trunc(v_jsrq,'IW')-1;
  SELECT COUNT(*)
    INTO v_zs
    ( SELECT v_ksrq + rn last_zr
            FROM (SELECT LEVEL-1 rn
                    FROM dual
                  CONNECT BY LEVEL <= v_dsdez_zr-v_ksrq + 1)
           WHERE to_char(v_ksrq + rn,'d') = '1' --Date interval Sunday (start date—           —Sunday of the penultimate week)
          UNION
SELECT trunc(v_jsrq,'IW') + 6 last_zr
            FROM dual --Sunday of the week where the end date is located
          );
  dbms_output.put_line('Start date:' || v_ksrq || ' , End date: '|| v_jsrq ||
                       ',Return the week number:' || v_zs);
  RETURN v_zs;
END get_weekly_times;
 

Guess you like

Origin blog.csdn.net/qq_36336332/article/details/103417587