ALTER FUNCTION "dba"."existid_panklist"( in "a_klass" char(20), in a_nimi char(50) default 'Uus pank' ) 
returns integer
begin
  declare ll_panknr integer;
  if Length(a_klass)>0 then
    if Length(a_klass)=3 then
      select "Min"("panklist"."panknr") into "ll_panknr" from "panklist" where Trim("panklist"."spank")="a_klass";
      if "ll_panknr" = 0 or "ll_panknr" is null then
        insert into "panklist"( "spank","spanknimi" ) values( "a_klass", a_nimi );
        select "Min"("panklist"."panknr") into "ll_panknr" from "panklist" where "panklist"."spank"="a_klass"
      end if;
    else
      select "Min"("panklist"."panknr") into "ll_panknr" from "panklist" where trim("panklist"."korresp")="a_klass";
      if "ll_panknr" = 0 or "ll_panknr" is null then
        insert into "panklist"( "korresp","spanknimi" ) values( "a_klass", a_nimi );
        select "Min"("panklist"."panknr") into "ll_panknr" from "panklist" where "panklist"."spank"="a_klass"
      end if;
    end if;
  end if;
  if ll_panknr is null then
    set ll_panknr=0
  end if;
  return("ll_panknr")
end