create or replace
PROCEDURE IMPOSTO_PEDIDO(
   P_FILIAL     IN FILIAL.CDFILIAL%TYPE,
   P_NRPEDIDO   IN PEDIDO.NRPEDIDO%TYPE)
IS
   V_EXISTEIMP INTEGER;
BEGIN
   DELETE FROM IMPOSNFTOTPED
   WHERE CDFILIAL  = P_FILIAL
     AND NRPEDIDO  = P_NRPEDIDO;

   FOR C_IMPOSITEMTOT IN (SELECT CDFILIAL, NRPEDIDO, CDIMPOSTO,
                                 SUM(VRIMPOSTOITPED) AS VRIMPOSTOTAL,
                                 SUM(VRBASECALCITPED) AS VRBASETOTAL
                            FROM IMPITEMPEDIDO
                           WHERE CDFILIAL  = P_FILIAL
                             AND NRPEDIDO  = P_NRPEDIDO
                          GROUP BY CDFILIAL, NRPEDIDO, CDIMPOSTO)
   LOOP
      V_EXISTEIMP := 0;
      SELECT COUNT(1)
        INTO V_EXISTEIMP
        FROM IMPOSNFTOTPED I, IMPOSTO T
       WHERE I.CDFILIAL  = P_FILIAL
         AND I.NRPEDIDO  = P_NRPEDIDO
         AND I.CDIMPOSTO = C_IMPOSITEMTOT.CDIMPOSTO
         AND I.CDIMPOSTO = T.CDIMPOSTO;
      IF V_EXISTEIMP = 0 THEN
         INSERT INTO IMPOSNFTOTPED
         (CDFILIAL, NRPEDIDO, CDIMPOSTO, VRTOTIMPPED, VRTOTBCALCPED)
         VALUES
         (C_IMPOSITEMTOT.CDFILIAL, C_IMPOSITEMTOT.NRPEDIDO, C_IMPOSITEMTOT.CDIMPOSTO, C_IMPOSITEMTOT.VRIMPOSTOTAL, C_IMPOSITEMTOT.VRBASETOTAL);
      ELSE
         UPDATE IMPOSNFTOTPED
            SET VRTOTIMPPED  = C_IMPOSITEMTOT.VRIMPOSTOTAL,
                VRTOTBCALCPED = C_IMPOSITEMTOT.VRBASETOTAL
          WHERE CDFILIAL  = C_IMPOSITEMTOT.CDFILIAL
            AND NRPEDIDO  = C_IMPOSITEMTOT.NRPEDIDO
            AND CDIMPOSTO = C_IMPOSITEMTOT.CDIMPOSTO;
      END IF;
   END LOOP;
END;
/