ALTER FUNCTION "dba"."get_doknr_mt"(in ai_years integer,in ai_objnr integer,in ai_sisse smallint,in ai_yksusnr integer)
returns char(20)
begin
  declare li_doknr integer;
  declare ls_doknr char(20);
  declare li_skoop integer;
  set ls_doknr='';
  select if ai_sisse=1 then mt_obj.mindoknrs else mt_obj.mindoknrv endif into li_doknr from mt_obj where mt_obj.objnr = ai_objnr;
  select mt_yksus.skoop into li_skoop from mt_yksus where mt_yksus.yksusnr = ai_yksusnr;
  if li_doknr = 0 then
    set ai_objnr=0;
    select if ai_sisse=1 then mt_konfm.mindoknrs else mt_konfm.mindoknrv endif, if mt_konfm.dok_auku=1 then 0 else li_skoop endif into li_doknr,li_skoop from mt_konfm where mt_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='mt_kanne' and tm_dok.aasta=ai_years and tm_dok.skoop=li_skoop and tm_dok.objnr=ai_objnr and tm_dok.sisse=ai_sisse;
    while exists(select 1 from mt_kanne left outer join mt_obj on mt_kanne.objnr = mt_obj.objnr left outer join mt_yksus on mt_kanne.yksusnr=mt_yksus.yksusnr where(mt_kanne.aasta = ai_years) and(mt_kanne.sisse = ai_sisse) and(mt_kanne.doknr = trim(str(li_doknr,20))) and((mt_kanne.objnr = ai_objnr) or (((ai_objnr = 0) and (mt_yksus.skoop=li_skoop or li_skoop=0)) and mt_obj.doknr = 1 and (if ai_sisse=1 then mt_obj.mindoknrs else mt_obj.mindoknrv endif) = 0 )) ) loop
      set li_doknr=li_doknr+1;
    end loop;
    while exists(select 1 from tm_resdok where (tm_resdok.tabel='mt_kanne') and (tm_resdok.aasta = ai_years) and (tm_resdok.skoop = li_skoop) and (tm_resdok.objnr = ai_objnr) and(tm_resdok.sisse = ai_sisse) and(tm_resdok.doknr = li_doknr) ) loop
      set li_doknr=li_doknr+1;
    end loop;
    if exists(select 1 from tm_dok where tm_dok.tabel='mt_kanne' and tm_dok.aasta=ai_years and tm_dok.skoop=li_skoop and tm_dok.objnr=ai_objnr and tm_dok.sisse=ai_sisse) then
      update tm_dok set doknr=li_doknr where tm_dok.tabel='mt_kanne' and tm_dok.aasta=ai_years and tm_dok.skoop=li_skoop and tm_dok.objnr=ai_objnr and tm_dok.sisse=ai_sisse
    else
      insert into tm_dok (tabel,aasta,skoop,objnr,sisse,doknr) values ('mt_kanne',ai_years,li_skoop,ai_objnr,ai_sisse,li_doknr)
    end if;
    set ls_doknr=trim(str(li_doknr,20))
  end if;
  return(ls_doknr)
end