CREATE FUNCTION "DBA"."get_eak_saajanr"( in a_regnr char(11),in a_nimi char(50),in a_code char(50))
RETURNS INTEGER
BEGIN
  declare ll_asutnr integer;
  declare ls_productversion char(100);
  if a_code is not null then
    select property('ProductVersion') into ls_productversion from DUMMY;
    if left(ls_productversion,1) in ('7','8') then
      set ll_asutnr=0;
    else
      if isnumeric(a_code)=1 then
        set ll_asutnr=convert(integer,a_code);
      else
        set ll_asutnr=0
      end if;
    end if;
    if ll_asutnr is null then
      set ll_asutnr=0
    end if;
    if ll_asutnr>0 then
      if Length(Trim(a_regnr))>0 then
        if not exists( select 1 from asulist where asutnr=ll_asutnr and reg_nr=a_regnr) then
          set ll_asutnr=0
        end if
      else
        set ll_asutnr=0
      end if;
    end if
  else
    set ll_asutnr=0;
  end if;
  if ll_asutnr=0 or ll_asutnr is null then
    set ll_asutnr=existid_asulist(a_regnr,a_nimi,'','')
  end if;
  return ll_asutnr;
END