CREATE FUNCTION "DBA"."get_pa_leping_tun_person"( in a_lepnr integer, in a_kuup date )
returns integer
begin
  declare ll_person integer;
  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;
  return ll_person
end