CREATE PROCEDURE "DBA"."pr_anal_arveld_kor"( in id_skoop integer, in a_konto char(7) )
BEGIN
  declare ld_kuup date;
  declare ls_order char(3);
  declare ll_asutnr integer;
  declare ll_partnr integer;
  declare ll_talnr integer;
  declare ll_alliknr integer;
  declare ll_ravonr integer;
  declare ldc_vahe numeric(15,2);
  declare err_notfound exception for sqlstate value '02000';
  declare c_gl_pr_koond1 dynamic scroll cursor for select if asutnr=0 then null else asutnr endif,if partnr=0 then null else partnr endif,if talnr=0 then null else talnr endif,if alliknr=0 then null else alliknr endif,if ravonr=0 then null else ravonr endif,ldeeb-lkree as comp_vahe from gl_dk_koond where comp_vahe<>0;
  set ls_order=existid_ordlist('X99');
  set ld_kuup=ymd(2016,1,1);
  open c_gl_pr_koond1;
  gl_pr_koond1_loop: loop
    fetch next c_gl_pr_koond1 into ll_asutnr,ll_partnr,ll_talnr,ll_alliknr,ll_ravonr,ldc_vahe;
    if sqlstate = err_notfound then -- kui eof
      leave gl_pr_koond1_loop
    end if;
    if ldc_vahe > 0 then
      insert into gl_pr_kanne(tulnud,kuup,doknr,summa,"order",deeb,skoop,user_code,asutnr,partnr,talnr,alliknr,ravonr)
        values('pr_anal_arveld_kor',ld_kuup,'korrigeerimine',ldc_vahe,ls_order,a_konto,id_skoop,32767,ll_asutnr,ll_partnr,ll_talnr,ll_alliknr,ll_ravonr);
    else
      insert into gl_pr_kanne(tulnud,kuup,doknr,summa,"order",kree,skoop,user_code,asutnr,partnr2,talnr,alliknr,ravonr)
        values('pr_anal_arveld_kor',ld_kuup,'korrigeerimine',abs(ldc_vahe),ls_order,a_konto,id_skoop,32767,ll_asutnr,ll_partnr,ll_talnr,ll_alliknr,ll_ravonr);
    end if
  end loop gl_pr_koond1_loop;
  close c_gl_pr_koond1;
END