CREATE FUNCTION "DBA"."get_kp_autoalus"( in a_asutnr integer, in a_nimi char(50) )
RETURNS INTEGER
BEGIN
  declare li_return integer;
  declare ll_count integer;
  if a_asutnr>0 then
    select count() into ll_count from kp_alus where kp_alus.asutnr=a_asutnr;
    if ll_count>0 then
      if ll_count=1 then
        select first kp_alus.alusnr into li_return from kp_alus where kp_alus.asutnr=a_asutnr
      elseif a_nimi is not null then
        select first kp_alus.alusnr into li_return from kp_alus where kp_alus.asutnr=a_asutnr and kp_alus.nimi=a_nimi
      end if;
    end if;
  end if;
  if li_return=0 then
    set li_return=null
  end if;
  return li_return;
END