ALTER FUNCTION "dba"."existid_kp_alus"( in a_nimi char(50), in a_konto char(7) default null, in a_asutnr integer default null, in a_saajanr integer default null, in a_meetnr integer default null, in a_kulnr integer default null, in a_talnr integer default null, in a_artnr integer default null, in a_tulnr integer default null, in a_objectnr integer default null, in a_osaknr integer default null, in a_subjectnr integer default null, in a_suundnr integer default null, in a_taotnr integer default null, in a_alliknr integer default null, in a_ravonr integer default null )
returns integer
begin
  declare ll_alusnr integer;
  select Min(kp_alus.alusnr) into ll_alusnr from kp_alus
    where kp_alus.nimi=a_nimi and
         (konto=a_konto or (konto is null and a_konto is null)) and
         (asutnr=a_asutnr or (asutnr is null and a_asutnr is null)) and
         (saajanr=a_saajanr or (saajanr is null and a_saajanr is null)) and
         (meetnr=a_meetnr or (meetnr is null and a_meetnr is null)) and
         (kulnr=a_kulnr or (kulnr is null and a_kulnr is null)) and
         (talnr=a_talnr or (talnr is null and a_talnr is null)) and
         (artnr=a_artnr or (artnr is null and a_artnr is null)) and
         (tulnr=a_tulnr or (tulnr is null and a_tulnr is null)) and
         (objectnr=a_objectnr or (objectnr is null and a_objectnr is null)) and
         (osaknr=a_osaknr or (osaknr is null and a_osaknr is null)) and
         (subjectnr=a_subjectnr or (subjectnr is null and a_subjectnr is null)) and
         (suundnr=a_suundnr or (suundnr is null and a_suundnr is null)) and
         (taotnr=a_taotnr or (taotnr is null and a_taotnr is null)) and
         (alliknr=a_alliknr or (alliknr is null and a_alliknr is null)) and
         (ravonr=a_ravonr or (ravonr is null and a_ravonr is null));
  if ll_alusnr = 0 or ll_alusnr is null then
    set ll_alusnr=getid_kp_alus();
    insert into kp_alus( alusnr,nimi,konto,asutnr,saajanr,meetnr,kulnr,talnr,artnr,tulnr,objectnr,osaknr,subjectnr,suundnr,taotnr,alliknr,ravonr,asutjad,saajajad,kontojad,meetjad,kuljad,taljad,artjad,tuljad,objectjad,osakjad,subjectjad,suundjad,taotjad,allikjad,ravojad)
      values( ll_alusnr,a_nimi,a_konto,a_asutnr,a_saajanr,a_meetnr,a_kulnr,a_talnr,a_artnr,a_tulnr,a_objectnr,a_osaknr,a_subjectnr,a_suundnr,a_taotnr,a_alliknr,a_ravonr,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) ;
  end if;
  return(ll_alusnr)
end