Oracle UDF【求两个日期之间工作日】

285 阅读1分钟
create or replace function networkday(p_date1 date,p_date2 date)
  return number
  -- 函数功能:返回两个日期之间工作日的天数
  -- 工作日定义:周一至周五
  is 
  p_num number;
  week_num number;
  mod_num number;
  extra_weekend number;
  rs number;
begin 
  -- 整周期外天数
  mod_num := mod(p_date2 - p_date1 + 1,7);
  
  -- 整周数
  week_num := (p_date2 - p_date1 + 1 - mod_num)/7;
  
  -- 起始日的负序号
  p_num := p_date1 - trunc(p_date1,'IW') - 7;
  
  -- 整周期外周末天数
  extra_weekend := case 
      when week_num > 0 and p_num = -2 and mod_num = 1 then 1
      when week_num > 0 and p_num = -2 and mod_num >= 2 then 2
      when week_num > 0 and p_num = -1 and mod_num >= 1 then 1
      when week_num > 0 then 0
      when p_num + mod_num - 1 >= -1 then 2
      when p_num + mod_num - 1 >= -2 then 1
      else 0 end;
  
  -- 中间工作日天数
  rs := p_date2 - p_date1 + 1  - (week_num * 2 + extra_weekend);
  return rs;
end;