CREATE OR REPLACE PROCEDURE CANCELA_ATIVO_EXP(
   P_CDFILIAL    IN FILIAL.CDFILIAL%TYPE,
   P_NRLANCTONF  IN NOTAFISCAL.NRLANCTONF%TYPE
) AS

   V_CTITEM   NUMBER;
BEGIN
   FOR C_ITEM IN (SELECT CDEMPRESA, IDSIMULOPERABEM, NRSEQCAPAOPEBEM,
                         NRSEQITCAPAOPE, NRSEQOPERABEM, CDBEMATIVO
                    FROM ITCAPAOPERABEM
                   WHERE CDFILIALNF = P_CDFILIAL
                     AND NRLANCTONF = P_NRLANCTONF
                   ORDER BY CDEMPRESA, IDSIMULOPERABEM, NRSEQCAPAOPEBEM)
   LOOP
      DELETE FROM ITCAPAOPERABEM
       WHERE CDEMPRESA = C_ITEM.CDEMPRESA
         AND IDSIMULOPERABEM = C_ITEM.IDSIMULOPERABEM
         AND NRSEQCAPAOPEBEM = C_ITEM.NRSEQCAPAOPEBEM
         AND NRSEQITCAPAOPE = C_ITEM.NRSEQITCAPAOPE;

      DELETE FROM OPERACAOBEM
       WHERE CDEMPRESA = C_ITEM.CDEMPRESA
         AND IDSIMULOPERACAO = C_ITEM.IDSIMULOPERABEM
         AND CDBEMATIVO = C_ITEM.CDBEMATIVO
         AND NRSEQOPERABEM = C_ITEM.NRSEQOPERABEM;

      SELECT COUNT(DISTINCT NRSEQCAPAOPEBEM)
        INTO V_CTITEM
        FROM ITCAPAOPERABEM
       WHERE CDEMPRESA = C_ITEM.CDEMPRESA
         AND IDSIMULOPERABEM = C_ITEM.IDSIMULOPERABEM
         AND NRSEQCAPAOPEBEM = C_ITEM.NRSEQCAPAOPEBEM;

      IF V_CTITEM = 0 THEN
         DELETE FROM CAPAOPERABEM
          WHERE CDEMPRESA = C_ITEM.CDEMPRESA
            AND IDSIMULOPERABEM = C_ITEM.IDSIMULOPERABEM
            AND NRSEQCAPAOPEBEM = C_ITEM.NRSEQCAPAOPEBEM;
      END IF;
   END LOOP;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('CANCELA_ATIVO_EXP','5.30.000'); END;
/