ALTER FUNCTION "dba"."if_exists_ls_maksud_id"( in a_asutnr integer, in a_yksusnr integer, in a_maksnr integer, in a_kuup date, in a_saajanr integer default null )
RETURNS INTEGER
BEGIN
  declare li_return integer;
  select first "ls_maksud"."id"
    into li_return
    from "ls_maksud" left outer join ls_kunde on ls_maksud.lapsnr=ls_kunde.lapsnr and ls_maksud.yksusnr=ls_kunde.yksusnr
                     left outer join ls_laps on ls_kunde.lapsnr=ls_laps.lapsnr
    where ("ls_maksud"."akuup"<=a_kuup and ("ls_maksud"."lkuup">=a_kuup or "ls_maksud"."lkuup" is null)) and
            ls_maksud.maksnr=a_maksnr and
            ls_maksud.yksusnr=a_yksusnr and
           (ls_laps.asutnr=a_asutnr or a_asutnr is null) and
           (ls_laps.saajanr=a_saajanr or a_saajanr is null);
  if li_return is null then
    set li_return = 0
  end if;
  return li_return;
END