ALTER PROCEDURE "dba"."pa_palgaleht"(in a_palgaleht integer,in a_v_aasta numeric(4), in a_valver smallint default 1)
begin
  delete from gl_tr_tabel;
  insert into gl_tr_tabel( "id",nimi,kree,deeb,adeeb)
    select pa_tasu.lepnr,
           Left(get_asulist_nimi(pa_leping.asutnr),100) as asulist_nimi,
           sum(if pa_taslist_a.sisse=0 then pa_tasu.summa else 0 endif),
           sum(if pa_taslist_a.sisse=0 then (pa_tasu.tulumaks+pa_tasu.tvtkmaks+pa_tasu.pensmaks) else if pa_taslist_a.algol='8o' then -1*(pa_tasu.tulumaks+pa_tasu.tvtkmaks+pa_tasu.pensmaks) else pa_tasu.summa-(pa_tasu.tulumaks+pa_tasu.tvtkmaks+pa_tasu.pensmaks) endif endif),
           sum(if pa_taslist_a.algol='8o' then pa_tasu.summa else 0 endif)
      from pa_tasu left outer join pa_taslist as pa_taslist_a on pa_tasu.tas_s = pa_taslist_a.tas_s
                   left outer join pa_leping on pa_tasu.lepnr = pa_leping.lepnr
      where pa_tasu.palgaleht=a_palgaleht and pa_tasu.v_aasta=a_v_aasta
      group by pa_tasu.lepnr,asulist_nimi;
  update gl_tr_tabel set ldeeb = adeeb-akree+deeb-kree,lkree = akree-adeeb+kree-deeb;
  update gl_tr_tabel set ldeeb = 0 where gl_tr_tabel.ldeeb < 0;
  update gl_tr_tabel set lkree = 0 where gl_tr_tabel.lkree < 0
end