CREATE FUNCTION "dba"."get_pa_leping_res_kuup2"( in a_resdefnr integer)
returns date
begin
  declare ld_kuup1 date;
  declare ld_kuup2 date;
  declare li_lepnr integer;
  declare li_peatnr integer;
  select if pl_resdef.lepnr is null then 0 else pl_resdef.lepnr endif, if pl_resdef.peatnr is null then 0 else pl_resdef.peatnr endif,if pl_resdef.kuup1 is null then pa_leping.kuup1 else pl_resdef.kuup1 endif into li_lepnr,li_peatnr,ld_kuup1 from pl_resdef left outer join pa_leping on pl_resdef.lepnr=pa_leping.lepnr where pl_resdef.resdefnr=a_resdefnr;
  if li_lepnr>0 and li_peatnr>0 then
    select first pl_resdef.kuup1 into ld_kuup2 from pl_resdef where pl_resdef.lepnr=li_lepnr and pl_resdef.peatnr=li_peatnr and pl_resdef.kuup1>ld_kuup1 order by pl_resdef.kuup1 asc;
    if ld_kuup2 is null then
      select pa_leping.kuup2 into ld_kuup2 from pa_leping where pa_leping.lepnr=li_lepnr;
    end if;
    if ld_kuup2 is null then
      set ld_kuup2=ymd(2999,1,1);
    end if;
  else
    set ld_kuup2=ymd(1999,1,1);
  end if;
  return ld_kuup2
end