CREATE FUNCTION "DBA"."pa_exists_summa_aastas_algol"(in a_a_aasta numeric(4),in a_lepnr integer,in a_algol char(2),in a_tasunr integer default 0) 
returns numeric(15,2)
begin
  declare ll_asutnr integer;
  declare ldc_summa numeric(15,2);
  if a_tasunr is null then
    set a_tasunr = 0
  end if;
-- tootaja kokku
  select pa_leping.asutnr into ll_asutnr from pa_leping where pa_leping.lepnr=a_lepnr;
  select sum(pa_tasu.summa) into ldc_summa from pa_tasu left outer join pa_leping on pa_tasu.lepnr=pa_leping.lepnr left outer join pa_taslist on pa_tasu.tas_s=pa_taslist.tas_s where pa_tasu.a_aasta = a_a_aasta and pa_leping.asutnr = ll_asutnr and pa_taslist.algol = a_algol and pa_tasu.tasunr <> a_tasunr;
  if ldc_summa is null then
    set ldc_summa = 0
  end if;
  return(ldc_summa)
end