CREATE FUNCTION "DBA"."existid_asulist_tp"(in a_regnr char(11),in a_nimi char(50),in a_enimi char(50) default '',in a_part char(16) default '')
returns integer
begin
  declare ll_asutnr integer;
  declare ll_partnr integer;
  declare ls_part char(16);
  if a_regnr is null then
    set a_regnr=''
  else
    set a_regnr=Trim(a_regnr)
  end if;
  if a_part is null then
    set a_part=''
  end if;
  if Length(a_regnr)>0 then
    select Min(asulist.asutnr) into ll_asutnr from asulist where asulist.reg_nr=a_regnr and asulist.nimi=a_nimi and(asulist.enimi=a_enimi or asulist.enimi is null)
  else
    select Min(asulist.asutnr) into ll_asutnr from asulist where asulist.nimi=a_nimi and(asulist.enimi=a_enimi or asulist.enimi is null)
  end if;
  if ll_asutnr=0 or ll_asutnr is null then
    if Length(a_regnr)>0 then
      select Min(asulist.asutnr) into ll_asutnr from asulist where asulist.reg_nr=a_regnr
    end if;
    if ll_asutnr=0 or ll_asutnr is null then
      set ll_partnr=null;
      if Length(a_regnr)=11 or a_part='800699' then
        select first partnr into ll_partnr from partlist where left(partlist.part,6) = '800699' and (partlist.lkuup is null or partlist.lkuup>Now())
      else
        if length(a_part)>2 then
          set ls_part='';
          select first vastlist.uus into ls_part from vastlist where vastlist.vana=left(a_part,3);
          if Length(ls_part)=3 then
            set a_part=ls_part+substring(a_part,4)
          end if;
          select first partnr into ll_partnr from partlist where Left(partlist.part,Length(a_part))=a_part and (partlist.lkuup is null or partlist.lkuup>Now())
        end if;
        if ll_partnr is null then
          select first partnr into ll_partnr from partlist where partlist.reg_nr=a_regnr and (partlist.lkuup is null or partlist.lkuup>Now());
          if ll_partnr is null then
            if Length(a_regnr)=8 and a_part='' then
              select first partnr into ll_partnr from partlist where left(partlist.part,6) = '800599' and (partlist.lkuup is null or partlist.lkuup>Now())
            end if
          end if
        end if
      end if;
      set ll_asutnr=getid_asulist();
      insert into asulist( asutnr,reg_nr,nimi,enimi,partnr) values( ll_asutnr,a_regnr,a_nimi,a_enimi,ll_partnr);
    end if
  end if;
  return(ll_asutnr)
end