ALTER FUNCTION "DBA"."existid_kblist"(in a_protsent numeric(10,3) default 0, in a_d_konto char(7) default null, in a_k_konto char(7) default null, in a_proportsioon numeric(10,3) default null, in a_prop_konto char(7) default null, in a_nimi char(25) default '')
returns integer
begin
  declare ll_kbnr integer;
  declare ls_nimi char(25);
  if a_protsent is null then
    select Min(kblist.kbnr) into ll_kbnr from kblist where kblist.protsent is null and (kblist.d_konto=a_d_konto or (kblist.d_konto is null and a_d_konto is null)) and (kblist.k_konto=a_k_konto or (kblist.k_konto is null and a_k_konto is null)) and (kblist.proportsioon is null or kblist.proportsioon=0);
  else
    if a_proportsioon is null or a_proportsioon=0 then
      select Min(kblist.kbnr) into ll_kbnr from kblist where kblist.protsent = a_protsent and (kblist.d_konto=a_d_konto or (kblist.d_konto is null and a_d_konto is null)) and (kblist.k_konto=a_k_konto or (kblist.k_konto is null and a_k_konto is null)) and (kblist.proportsioon is null or kblist.proportsioon=0);
    else
      select Min(kblist.kbnr) into ll_kbnr from kblist where kblist.protsent = a_protsent and (kblist.d_konto=a_d_konto or (kblist.d_konto is null and a_d_konto is null)) and (kblist.k_konto=a_k_konto or (kblist.k_konto is null and a_k_konto is null)) and (kblist.proportsioon=a_proportsioon) and (kblist.prop_konto=a_prop_konto or (kblist.prop_konto is null and a_prop_konto is null));
    end if;
    if ll_kbnr=0 or ll_kbnr is null then
      set ll_kbnr=getid_kblist();
      if ll_kbnr>0 then
        if Length(a_nimi)>0 then
          set ls_nimi=a_nimi
        else
          if a_protsent is null then
            set ls_nimi='NULL'
          else
            set ls_nimi=convert(char(25),a_protsent)+'%'
          end if
        end if;
        insert into kblist(kbnr,nimi,protsent,d_konto,k_konto,proportsioon,prop_konto) values(ll_kbnr,ls_nimi,a_protsent,a_d_konto,a_k_konto,a_proportsioon,a_prop_konto);
      else
        set ll_kbnr=null;
      end if;
    end if;
  end if;
  return(ll_kbnr)
end