CREATE FUNCTION "DBA"."get_pa_leping_tun_ntn"( in a_lepnr integer, in a_kuup date )
returns numeric(6,3)
begin
  declare ldc_ntn numeric(6,3);
  select first pa_leping_tun.ntn into ldc_ntn 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 ldc_ntn=0 or ldc_ntn is null then
    select if id_koht=1 then 40 else 0 endif into ldc_ntn from pa_leping where pa_leping.lepnr=a_lepnr
  end if;
  if ldc_ntn is null then
    set ldc_ntn=0
  end if;
  return ldc_ntn
end