DECLARE
   V_VRNOTAFISC DOUBLE PRECISION;
   V_VRIMPOSTO  DOUBLE PRECISION;
   V_CDENCARGO  VARCHAR2(02);
BEGIN
   FOR C_NOTA IN (SELECT DISTINCT N.CDFILIAL, N.NRLANCTONF
                    FROM NOTAFISCAL N, ITEMPRODUTO IT
                   WHERE IDENTRSAIDOP = 'S'
                     AND DTENTRSAID BETWEEN '01/01/2011' AND '30/06/2011'
                     AND IT.CDFILIAL = N.CDFILIAL
                     AND IT.NRLANCTONF = N.NRLANCTONF
                     AND EXISTS (SELECT CDFILIAL
                                   FROM ITEMPROIMPOS I
                                  WHERE N.CDFILIAL = IT.CDFILIAL
                                    AND N.NRLANCTONF = IT.NRLANCTONF
                                    AND I.NRSEQITPROD = IT.NRSEQITPROD
                                    AND I.CDIMPOSTO = '05')) LOOP
      SELECT SUM(VRTOTIMPONF)
        INTO V_VRIMPOSTO
        FROM IMPOSNFTOT
       WHERE CDFILIAL = C_NOTA.CDFILIAL
         AND NRLANCTONF = C_NOTA.NRLANCTONF
         AND CDIMPOSTO = '05';

      IF V_VRIMPOSTO > 0 THEN
         SELECT MAX(CDENCARGO)
           INTO V_CDENCARGO
           FROM ITEMENCARGO
          WHERE CDFILIAL = C_NOTA.CDFILIAL
            AND NRLANCTONF = C_NOTA.NRLANCTONF
            AND CDENCARGO = '08';

         IF V_CDENCARGO = '08' THEN
            UPDATE ITEMENCARGO
               SET VRITEMENCA = V_VRIMPOSTO
             WHERE CDFILIAL = C_NOTA.CDFILIAL
               AND NRLANCTONF = C_NOTA.NRLANCTONF
               AND CDENCARGO = '08';
         ELSE
            INSERT INTO ITEMENCARGO
            (CDFILIAL, NRLANCTONF, CDENCARGO, VRITEMENCA)
            VALUES
            (C_NOTA.CDFILIAL, C_NOTA.NRLANCTONF, '08', V_VRIMPOSTO);
         END IF;
         UPDATE ITEMPROIMPOS
            SET CDIMPOSTO = '00'
          WHERE CDFILIAL = C_NOTA.CDFILIAL
            AND NRLANCTONF = C_NOTA.NRLANCTONF
            AND CDIMPOSTO = '05';

         UPDATE IMPOSTONF
            SET CDIMPOSTO = '00'
          WHERE CDFILIAL = C_NOTA.CDFILIAL
            AND NRLANCTONF = C_NOTA.NRLANCTONF
            AND CDIMPOSTO = '05';

         UPDATE IMPOSNFTOT
            SET CDIMPOSTO = '00'
          WHERE CDFILIAL = C_NOTA.CDFILIAL
            AND NRLANCTONF = C_NOTA.NRLANCTONF
            AND CDIMPOSTO = '05';
      END IF;
   END LOOP;
   COMMIT;
END;
/