ALTER FUNCTION "dba"."get_doknr_dk"(in ai_years integer,in ai_objnr integer)
returns char(20)
begin
  declare li_doknr integer;
  declare ls_doknr char(20);
  declare li_spank smallint;
  declare li_skoop integer;
  set ls_doknr='';
  select dk_obj.mindoknrs,dk_obj.spank,dk_obj.skoop into li_doknr,li_spank,li_skoop from dk_obj where dk_obj.objnr = ai_objnr;
  if li_doknr = 0 then
    set ai_objnr=0;
    select if li_spank=1 then if dk_konfm.mindoknrv is null or dk_konfm.mindoknrv<=0 then 1 else dk_konfm.mindoknrv endif else if dk_konfm.mindoknrs is null or dk_konfm.mindoknrs<=0 then 1 else dk_konfm.mindoknrs endif endif, if dk_konfm.dok_auku=1 then 0 else li_skoop endif into li_doknr,li_skoop from dk_konfm where dk_konfm.id =1;
  end if;
  select first if dk_kanne_dok.doknr is null or li_doknr>dk_kanne_dok.doknr then li_doknr else dk_kanne_dok.doknr endif into li_doknr from dk_kanne_dok where dk_kanne_dok.aasta=ai_years and dk_kanne_dok.skoop=li_skoop and dk_kanne_dok.objnr=ai_objnr and dk_kanne_dok.sisse=li_spank;
  while exists(select 1 from dk_kanne left outer join dk_obj on dk_kanne.objnr = dk_obj.objnr where(Years(dk_kanne.arvekuup) = ai_years) and(dk_kanne.doknr = trim(str(li_doknr,20))) and((dk_kanne.objnr = ai_objnr) or (((ai_objnr = 0) and (dk_obj.skoop=li_skoop or li_skoop=0)) and dk_obj.spank = li_spank and dk_obj.mindoknrs = 0 ))) loop
    set li_doknr=li_doknr+1;
  end loop;
  if exists(select 1 from dk_kanne_dok where dk_kanne_dok.aasta=ai_years and dk_kanne_dok.skoop=li_skoop and dk_kanne_dok.objnr=ai_objnr and dk_kanne_dok.sisse=li_spank) then
    update dk_kanne_dok set doknr=li_doknr where dk_kanne_dok.aasta=ai_years and dk_kanne_dok.skoop=li_skoop and dk_kanne_dok.objnr=ai_objnr and dk_kanne_dok.sisse=li_spank
  else
    insert into dk_kanne_dok (aasta,skoop,objnr,sisse,doknr) values (ai_years,li_skoop,ai_objnr,li_spank,li_doknr)
  end if;
  set ls_doknr=trim(str(li_doknr,20));
  return(ls_doknr)
end