ALTER PROCEDURE "dba"."kp_kanne_delete"( in a_objnr integer, in a_perlop date )
BEGIN
  declare ldc_summa numeric(15,2);
  if a_objnr > 0 then
    -- JAAK
    select sum(if kp_kanne.sisse=1 then kp_kanne.summa else (-1)*kp_kanne.summa endif) into ldc_summa from kp_kanne where kp_kanne.objnr=a_objnr and kp_kanne.kuup<=a_perlop;
    -- KUSTUTAMINE
    delete kp_kanne where kp_kanne.objnr=a_objnr and kp_kanne.kuup<=a_perlop;
    -- LISAMINE
    if ldc_summa is not null and ldc_summa<>0 then
      insert into kp_kanne(objnr,tulnud,sisse,kuup,summa,doknr,user_code)
        values (a_objnr,'kustutamine 1',1,a_perlop,ldc_summa,'1',32767);
    end if
  end if;
END