CREATE FUNCTION "DBA"."get_tp_enne_kuup"( in a_kuup date, in a_pva integer)
returns date
begin
  declare ld_return date;
  set ld_return=ymd(2000,1,1);
  if a_kuup is not null and a_pva > 0 then
    per_loop: while a_pva > 0 loop
      set a_kuup=Days(a_kuup,-1);
      if dow(a_kuup) > 1 and dow(a_kuup) < 7 then
        if not exists(select 1 from pyhalist where pyhalist.pyhakuup = a_kuup) then
          set a_pva=a_pva-1
        end if
      end if;
    end loop per_loop;
    set ld_return=a_kuup;
  end if;
  return(ld_return)
end