CREATE TABLE USR_CONTAPAGAR
(CDFILIAL         VARCHAR2(4),
 NRLANCTONF       VARCHAR2(10),
 NRSEQVENPAG      VARCHAR2(2),
 NRSEQCOUNT       VARCHAR2(2))
/

CREATE TABLE USR_CTRLFILIAL
(CDFILIAL         VARCHAR2(4),
 constraint PK_USR_CTRLFILIAL primary key (CDFILIAL))
/

CREATE OR REPLACE PROCEDURE PREENCHE_TABELA
AS
   V_NRSEQVENPAG  VARCHAR2(02);
   V_CDCHAVECONT  VARCHAR2(14);
   V_CDFILIAL     VARCHAR2(04);
BEGIN
   SELECT MAX(CDFILIAL)
   INTO V_CDFILIAL
   FROM PARAMGERAL;

   V_CDCHAVECONT := '00';

   FOR C IN (SELECT CP1.CDFILIAL, CP1.NRLANCTONF, NRSEQVENPAG
             FROM NOTAFISCAL NF1, CONTAPAGAR CP1
             WHERE (NF1.CDFILIAL     = V_CDFILIAL)                          AND
                   (NF1.IDSTATUS     = 'A')                                 AND
                   (NF1.DTENTRSAID <= SYSDATE)                              AND
                   (NF1.DTEXPORTACAO IS NULL)                               AND
                   ((NF1.IDORIGDESTNF IS NULL) OR (NF1.IDORIGDESTNF = 'F')) AND
                   (CP1.CDFILIAL     = NF1.CDFILIAL)                        AND
                   (CP1.NRLANCTONF   = NF1.NRLANCTONF)
             GROUP BY CP1.CDFILIAL, CP1.NRLANCTONF, NRSEQVENPAG) LOOP

      IF (V_CDCHAVECONT <> C.CDFILIAL||C.NRLANCTONF) THEN
         V_NRSEQVENPAG := '01';
      ELSE
         V_NRSEQVENPAG := LPAD(TO_CHAR(TO_NUMBER(V_NRSEQVENPAG) + 1),2,'0');
      END IF;

      INSERT INTO USR_CONTAPAGAR
         (CDFILIAL, NRLANCTONF, NRSEQVENPAG, NRSEQCOUNT)
      VALUES
         (C.CDFILIAL, C.NRLANCTONF, C.NRSEQVENPAG, V_NRSEQVENPAG);

      V_CDCHAVECONT := C.CDFILIAL||C.NRLANCTONF;
   END LOOP;
END;
/


-- VERSAO --
BEGIN ATUVEROBJ('PREENCHE_TABELA','5.01.001'); END;
/

