ALTER FUNCTION "DBA"."get_otsek_service_id"( in a_serviceid char(30), in a_asutnr integer default 0, in a_kuup date default now())
RETURNS INTEGER
begin
  declare li_servicenr integer;
  set a_serviceid=Trim(a_serviceid);
  if a_asutnr>0 then
    select asulist.servicenr into li_servicenr from asulist where asulist.asutnr=a_asutnr
  end if;
  if li_servicenr is null and Length(a_serviceid)>0 and a_asutnr>0 then
    select first servicenr into li_servicenr from otsek_service where serviceid=a_serviceid and asutnr=a_asutnr and akuup<=a_kuup and (lkuup>=a_kuup or lkuup is null)
  end if;
  if li_servicenr=0 then
    set li_servicenr=null
  end if;
  return li_servicenr;
end