BEGIN
   FOR CUR_FIL IN (
   SELECT F.CDFILIAL, LPAD(TO_CHAR(TO_NUMBER(F.CDFILIAL)),2,'0') AS CDEXPORTEMPR
   FROM FILIAL F, PARAMEMPRESA P
   WHERE F.CDEMPRESA = P.CDEMPRESA
   ORDER BY F.CDFILIAL) LOOP

      UPDATE NOTAFISCAL
      SET DTEXPORTACAO = SYSDATE
      WHERE (CDFILIAL, NRLANCTONF) IN (SELECT NF.CDFILIAL, NF.NRLANCTONF
                                       FROM NOTAFISCAL NF, CONTARECEBER CR
                                       WHERE (NF.CDFILIAL   = CR.CDFILIAL)        AND
                                             (NF.NRLANCTONF = CR.NRLANCTONF)      AND
                                             (CR.NRLANCTODUP IS NOT NULL)         AND
                                             (NF.CDFILIEMIT   = CUR_FIL.CDFILIAL) AND
                                             (NF.IDENTRSAIDOP = 'S')              AND
                                             (NF.CDTIPOOPER   = '01')             AND
                                             (NF.IDSTATUS IN ('A','E'))           AND
                                             (NF.DTEXPORTACAO IS NULL)            AND
                                             (NF.DTEMISSAO <= SYSDATE));

      UPDATE NOTAFISCAL
      SET DTEXPORTACAO = SYSDATE
      WHERE (CDFILIAL, NRLANCTONF) IN (SELECT NF.CDFILIAL, NF.NRLANCTONF
                                       FROM NOTAFISCAL NF
                                       WHERE (NF.CDFILIRECE   = CUR_FIL.CDFILIAL) AND
                                             (NF.IDSTATUS     = 'A')              AND
                                             (NF.IDENTRSAIDOP = 'E')              AND
                                             (NVL(NF.IDORIGDESTNF,'F') = 'F')     AND
                                             (NF.DTEXPORTACAO IS NULL)            AND
                                             (NF.DTENTRSAID <= SYSDATE)
                                       UNION ALL
                                       SELECT NF.CDFILIAL, NF.NRLANCTONF
                                       FROM NOTAFISCAL NF
                                       WHERE (NF.CDFILIEMIT = CUR_FIL.CDFILIAL) AND
                                             (NF.IDSTATUS IN ('A','E'))         AND
                                             (NF.CDTIPOOPER   = '06')           AND
                                             (NF.IDENTRSAIDOP = 'S')            AND
                                             (NF.IDORIGDESTNF = 'F')            AND
                                             (NF.DTEXPORTACAO IS NULL)          AND
                                             (NF.DTEMISSAO <= SYSDATE));
   END LOOP;
END;
/

TRUNCATE TABLE USR_CONTAPAGAR;


