CREATE OR REPLACE FUNCTION WEEKENDDAY( IN_APP_DATE IN DATE)
RETURN integer IS
my_lastdate DATE;
my_nextsunday DATE;
my_weeks integer;
my_n_diff integer;
my_remain integer;
my_dws integer;
my_dwe integer;
out_count integer :=0;
BEGIN
my_lastdate:=LAST_DAY(IN_APP_DATE);
select NEXT_DAY(IN_APP_DATE,1) INTO my_nextsunday from dual;
my_n_diff:=TRUNC( ( my_lastdate - my_nextsunday ), 0 )+1;
if(my_nextsunday<=my_lastdate) THEN
my_weeks:=FLOOR(my_n_diff/7);
my_remain:=mod(my_n_diff,7);
if my_remain>0 THEN
out_count:=1;
END IF;
out_count:=out_count+my_weeks*2;
IF to_number(to_char(IN_APP_DATE,'D'))=1 THEN
out_count:=out_count+2;
ELSE
out_count:=out_count+1;
END IF;
ELSE
my_dws:=to_number(to_char(IN_APP_DATE,'D'));
my_dwe:=to_number(to_char(my_lastdate,'D'));
IF my_dws<=my_dwe THEN
IF my_dws=1 THEN
out_count:=out_count+1;
END IF;
IF my_dwe=7 THEN
out_count:=out_count+1;
END IF;
ELSE
out_count:=2;
END IF;
end if;
return out_count;
END WEEKENDDAY;