CREATE FUNCTION "DBA"."get_eak_objnr"( in a_id_dk_earve integer, in a_id_dk_earve_rida integer, in a_objnr integer )
RETURNS integer
BEGIN
  declare ll_objnr integer;
  declare ll_skoop integer;
  declare ls_obj_konto char(7);
  if a_id_dk_earve>0 then
    select if "authlist"."skoop" is null then "dk_earve"."skoop" else "authlist"."skoop" endif into ll_skoop from "dk_earve" left outer join "authlist" on "dk_earve"."authnr"="authlist"."authnr" where "dk_earve"."id"=a_id_dk_earve;
    if a_id_dk_earve_rida>0 then
      select if (obj_konto is null or Length(Trim(obj_konto))=0) then '201000' else obj_konto endif into ls_obj_konto from "dk_earve_rida" where "dk_earve_rida"."id_dk_earve"=a_id_dk_earve and "dk_earve_rida"."id"=a_id_dk_earve_rida
    end if
  end if;
  if ll_skoop is null then
    select first objnr into ll_objnr from dk_obj where djkonto=ls_obj_konto order by skoop;
  else
    select first objnr into ll_objnr from dk_obj where (skoop=ll_skoop or ll_skoop=0) and djkonto=ls_obj_konto order by skoop;
  end if;
  if ll_objnr is null or ll_objnr=0 then
    if ll_skoop is null then
      select first objnr into ll_objnr from dk_obj where spank=1 order by skoop;
    else
      select first objnr into ll_objnr from dk_obj where (skoop=ll_skoop or ll_skoop=0) and spank=1 order by skoop;
    end if;
  end if;
  if (ll_objnr is null or ll_objnr=0) and a_objnr>0 then
    set ll_objnr=a_objnr
  end if;
  return ll_objnr;
END