CREATE FUNCTION "DBA"."get_pa_leping_tun_amet"( in a_lepnr integer, in a_kuup date )
returns char(100)
begin
  declare ll_person integer;
  declare ls_amet char(100);
  select first pa_leping_tun.person into ll_person from pa_leping_tun where pa_leping_tun.lepnr=a_lepnr and pa_leping_tun.kuup1 <= a_kuup order by pa_leping_tun.kuup1 desc;
  if ll_person is null then
    select person into ll_person from pa_leping where pa_leping.lepnr=a_lepnr
  end if;
  if ll_person is null then
    set ls_amet=''
  else
    select ametlist.nimi into ls_amet from ametlist where ametlist.person=ll_person
  end if;
  return ls_amet
end