CREATE FUNCTION "dba"."existid_periood"( in a_mkt integer, in a_peralg date, in a_perlop date, in a_id_user integer) 
returns integer
begin
  declare ll_id integer;
  set ll_id=0;
  if a_id_user>0 then
    select first tm_per."id" into ll_id from tm_per where id_user=a_id_user and u_mkt=a_mkt and u_peralg=a_peralg and u_perlop=a_perlop;
    if ll_id = 0 or ll_id is null then
      set ll_id=getid_periood();
      if ll_id > 0 then
        insert into tm_per("id",id_user,u_mkt,u_peralg,u_perlop) values(ll_id,a_id_user,a_mkt,a_peralg,a_perlop);
      end if;
    end if;
  end if;
  return(ll_id)
end