ALTER FUNCTION "DBA"."existid_partlist"( in a_part char(16), in a_regnr char(11) default '' ) 
returns integer
begin
  declare ll_partnr integer;
  declare ls_part char(16);
  set ll_partnr=null;
  if a_regnr is null then
    set a_regnr=''
  end if;
  -- otsi originaal TP koodi
  if length(a_part)>5 then
    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;
  -- otsi registrikoodi jargi
  if ll_partnr is null and length(a_regnr)=8 then
    select first partnr into ll_partnr from partlist where partlist.reg_nr=a_regnr and (partlist.lkuup is null or partlist.lkuup>Now());
  end if;
  -- otsi asendatud TP koodi jargi
  if ll_partnr is null and length(a_part)>5 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);
      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;
  end if;
  if ll_partnr is null then
    set ll_partnr=getid_partlist();
    insert into partlist( partnr,part,nimi ) values( ll_partnr,a_part,'Uus tehingupartner' ) ;
  end if;
  return(ll_partnr)
end