ALTER FUNCTION "dba"."get_doknr_ea"(in ai_years integer,in ai_objnr integer)
returns char(20)
begin
  declare li_doknr integer;
  declare ls_doknr char(20);
  declare li_skoop integer;
  set ls_doknr='';
  select ea_obj.mindoknrs,ea_obj.skoop into li_doknr,li_skoop from ea_obj where ea_obj.objnr = ai_objnr;
  if li_doknr = 0 then
    set ai_objnr=0;
    select ea_konfm.mindoknrs, if ea_konfm.dok_auku=1 then 0 else li_skoop endif into li_doknr,li_skoop from ea_konfm where ea_konfm.id =1;
    if li_doknr is null or li_doknr <= 0 then
      set li_doknr=1
    end if;
  end if;
  if li_doknr > 0 then
    select first if tm_dok.doknr is null or li_doknr>tm_dok.doknr then li_doknr else tm_dok.doknr endif into li_doknr from tm_dok where tm_dok.tabel='ea_kanne' and tm_dok.aasta=ai_years and tm_dok.skoop=li_skoop and tm_dok.objnr=ai_objnr and tm_dok.sisse=1;
    while exists(select 1 from ea_kanne left outer join ea_obj on ea_kanne.objnr = ea_obj.objnr where(ea_kanne.aasta = ai_years) and(ea_kanne.doknr = trim(str(li_doknr,20))) and((ea_kanne.objnr = ai_objnr) or (((ai_objnr = 0) and (ea_obj.skoop=li_skoop or li_skoop=0)) and ea_obj.doknr = 1 and ea_obj.mindoknrs = 0 )) ) loop
      set li_doknr=li_doknr+1;
    end loop;
    if exists(select 1 from tm_dok where tm_dok.tabel='ea_kanne' and tm_dok.aasta=ai_years and tm_dok.skoop=li_skoop and tm_dok.objnr=ai_objnr and tm_dok.sisse=1) then
      update tm_dok set doknr=li_doknr where tm_dok.tabel='ea_kanne' and tm_dok.aasta=ai_years and tm_dok.skoop=li_skoop and tm_dok.objnr=ai_objnr and tm_dok.sisse=1
    else
      insert into tm_dok (tabel,aasta,skoop,objnr,sisse,doknr) values ('ea_kanne',ai_years,li_skoop,ai_objnr,1,li_doknr)
    end if;
    set ls_doknr=trim(str(li_doknr,20))
  end if;
  return(ls_doknr)
end