CREATE PROCEDURE "dba"."pr_kontroll_kp"( in id_skoop integer,in perlop date, in a_konto char(7))
BEGIN
  delete from gl_dk_koond;
  delete from gl_pr_koond;
-- Kassa/pank
  insert into gl_pr_koond(konto,adeeb)
      select '2',
             sum(if kp_kanne.sisse=0 then kp_kanne.summa else (-1)*kp_kanne.summa endif)
        from kp_kanne key join kp_obj
        where (kp_obj.skoop=id_skoop) and kp_obj.konto=a_konto and kp_kanne.kuup<=perlop;

-- Deebet
  insert into gl_pr_koond(konto,deeb)
      select '5',
             sum(pr_kanne.summa)
        from pr_kanne
        where (pr_kanne.skoop=id_skoop) and pr_kanne.deeb=a_konto and pr_kanne.kuup<=perlop;
-- Kreedit
  insert into gl_pr_koond(konto,kree)
      select '6',
             sum(pr_kanne.summa)
        from pr_kanne
        where (pr_kanne.skoop=id_skoop) and pr_kanne.kree=a_konto and pr_kanne.kuup<=perlop;
-- Koond
  insert into gl_dk_koond( konto,adeeb,deeb)
    select '5',sum(gl_pr_koond.adeeb),
               sum(gl_pr_koond.deeb-gl_pr_koond.kree)
      from gl_pr_koond;
END