CREATE OR REPLACE TRIGGER USR_ATUALIZA_ITEMENCARGO_NF
AFTER DELETE  ON ITEMPROIMPOS  FOR EACH ROW
DECLARE
  V_IDENTRSAIDOP VARCHAR2(01);
  V_CDCLIENTE    VARCHAR2(21);
  V_CDGRUPOFISC  VARCHAR2(03);
  V_VRIMPOSTO    DOUBLE PRECISION;
  V_VRNOTAFISC   DOUBLE PRECISION;
  V_CDTIPOOPER   VARCHAR2(02);
  V_CDEMPRESA    VARCHAR2(02);
  V_CDINSCESTA   VARCHAR2(16);
  V_CDFORNECED   VARCHAR2(21);
  V_CDFILIRECE   VARCHAR2(04);
  V_IDSISTEMA    VARCHAR2(03);
  V_DTENTRSAID   DATE;
  V_ORIGDESTNF   VARCHAR2(01);
  V_CDFILIEMIT   VARCHAR2(04);
  V_NRLANCESTQ   VARCHAR2(10);

BEGIN

   SELECT MAX(IDENTRSAIDOP), MAX(CDCLIENTE), MAX(CDTIPOOPER), MAX(CDEMPRESA),
          MAX(CDINSCESTA), MAX(CDTIPOOPER), MAX(CDCLIENTE),    MAX(CDFORNECED),
          MAX(CDFILIRECE), MAX(DTENTRSAID), MAX(IDORIGDESTNF), MAX(CDFILIEMIT),
          MAX(IDSISTEMA)
     INTO V_IDENTRSAIDOP, V_CDCLIENTE, V_CDTIPOOPER, V_CDEMPRESA,
          V_CDINSCESTA, V_CDTIPOOPER, V_CDCLIENTE, V_CDFORNECED,
          V_CDFILIRECE, V_DTENTRSAID, V_ORIGDESTNF, V_CDFILIEMIT,
          V_IDSISTEMA
     FROM NOTAFISCAL
    WHERE CDFILIAL = :OLD.CDFILIAL
      AND NRLANCTONF = :OLD.NRLANCTONF;

   IF V_IDENTRSAIDOP = 'S' THEN

      SELECT MAX(CDGRUPOFISC)
        INTO V_CDGRUPOFISC
        FROM CLIENTE
       WHERE CDCLIENTE = V_CDCLIENTE;

      IF V_CDGRUPOFISC = '001' THEN

         IF :OLD.CDIMPOSTO = '00' THEN

            IF :OLD.VRIMPOSTOIT > 0  THEN
                   UPDATE ITEMENCARGO
                  SET VRITEMENCA = 0
                WHERE CDFILIAL = :OLD.CDFILIAL
                  AND NRLANCTONF = :OLD.NRLANCTONF
                  AND CDENCARGO = '08';
            END IF;
         END IF;
      END IF;
  END IF;
END;
/
