Friday, January 11, 2013

Function to return a monthly period


Question: How can I create a function that returns the period that correspond to a month?
A period starts on the first Monday of the month, and ends on a Sunday. If the Sunday does not fall on the 30th or 31st, the procedure should choose the first Sunday of the next month.
For example, the function should return something like this (startdate - enddate):
Oct 6, 2003 - Nov 2, 2003
Answer: Below is a function that accepts as input a date value formatted as 'yyyy/mm/dd'. The function takes this date and returns the period that the date falls within.
create or replace function get_period (pDate varchar2)
   return varchar2
is
   v_period_start date;
   v_period_end date;
   v_check_date date;
   
begin

   /* Determine the 1st of the month */
   v_check_date := trunc(to_date(pDate, 'yyyy/mm/dd'),'MM');
   
   /* Find first monday */
   loop
      exit when to_number(to_char(v_check_date,'d')) = 2;
      v_check_date := v_check_date + 1;
   end loop;
   
   v_period_start := v_check_date;
   
   /* Determine last sunday of current month */
   v_period_end := v_period_start + 27;
   
   /* Take the sunday in next month if the sunday falls */
   /* on the 29th or earlier */
   if to_number(to_char(v_period_end, 'dd')) < 30 then
      v_period_end := v_period_end + 7;
   end if;
   
   return v_period_start || ' - ' || v_period_end;
   
end get_period ;