ALTER FUNCTION "dba"."existid_asulist"(in a_regnr char(11),in a_nimi char(100),in a_aadr char(150),in a_enimi char(50) default '')
returns integer
begin
  declare ll_asutnr integer;
  declare ll_partnr integer;
  declare ls_enimi char(50);
  declare ls_aadr1 char(40);
  declare ls_aadr2 char(40);
  declare ls_aadr3 char(40);
  set a_regnr=Trim(a_regnr);
  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
    else
      set a_regnr=''
    end if;
    if ll_asutnr = 0 or ll_asutnr is null then
      set ls_aadr1=substring(a_aadr,1,40);
      set ls_aadr2=substring(a_aadr,41,40);
      set ls_aadr3=substring(a_aadr,81,40);
      if Length(Trim(a_enimi))>0 then
        set ls_enimi=a_enimi
      else
        set ls_enimi=null
      end if;
      set ll_partnr = null;
      if Length(Trim(a_regnr)) > 7 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(Trim(a_regnr)) > 10 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
            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
      else
        select first partnr into ll_partnr from partlist where left(partlist.part,6) = '800699' and (partlist.lkuup is null or partlist.lkuup>Now());
      end if;
      insert into asulist( reg_nr,nimi,enimi,aadr1,aadr2,aadr3,partnr) values( a_regnr,a_nimi,ls_enimi,ls_aadr1,ls_aadr2,ls_aadr3,ll_partnr) ;
      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);
    end if
  end if;
  return(ll_asutnr)
end