CREATE OR REPLACE PROCEDURE TAB_NATUOPER_494(
   P_CDEMPRESA    IN NOTAFISCAL.CDEMPRESA%TYPE,
   P_NRINSJURFILI IN FILIAL.NRINSJURFILI%TYPE,
   P_CDIMPOSTO    IN IMPOSTONF.CDIMPOSTO%TYPE,
   P_DTINICIAL    IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_DTFINAL      IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_NRSEQARQMAG  IN ARQMAGNETICO.NRSEQARQMAG%TYPE)
AS
   V_SEQUNCIAL NUMBER;
   V_DATA_ATU  VARCHAR2(08);
BEGIN

   FOR C_TMP IN (SELECT CDREGISTRO, CDCHAVEREG, CDCAMPO1,
                        (CASE WHEN SUBSTR(CDCHAVEREG,1,1) IN ('1','2','3') THEN 'E' ELSE 'S' END) AS IDENTRSAIDOP
                   FROM TMP_REGDADOS_IN86
                  WHERE CDREGISTRO = '494' ) LOOP

      FOR C_NATUOPER IN (SELECT DISTINCT RPAD(NVL(C_TMP.CDCHAVEREG, ' '), 6, ' ')||
                                RPAD(NVL(SUBSTR(MAX(C.DSCDFISCOPER),1,45), ' '), 45, ' ') AS DSARQMAG, C_TMP.CDCHAVEREG
                           FROM CODFISCOPER C
                          WHERE C.CDEMPRESA    = P_CDEMPRESA
                            AND C.CDFISCOPER   = SUBSTR(C_TMP.CDCHAVEREG,2,3)
                            AND C.IDENTRSAIDOP = C_TMP.IDENTRSAIDOP
                            AND C.IDENTSAICFOP = C_TMP.IDENTRSAIDOP
                         GROUP BY RPAD(NVL(C_TMP.CDCHAVEREG, ' '), 6, ' '), C_TMP.CDCHAVEREG
                         ORDER BY C_TMP.CDCHAVEREG) LOOP

         SELECT RPAD(TO_CHAR(MIN(DTEMISSAO), 'DDMMYYYY'), 8, ' ')
           INTO V_DATA_ATU
           FROM (SELECT DTEMISSAO
                   FROM NOTAFISCAL N, TMP_REGDADOS_IN86 T
                  WHERE N.CDFILIAL = SUBSTR(T.CDCHAVEREG,1,4)
                    AND N.NRLANCTONF = SUBSTR(T.CDCHAVEREG,5,10)
                    AND T.CDREGISTRO = '431'
                 UNION ALL
                 SELECT DTEMISSAO
                   FROM NOTAFISCAL N, TMP_REGDADOS_IN86 T
                  WHERE N.CDFILIAL = SUBSTR(T.CDCHAVEREG,1,4)
                    AND N.NRLANCTONF = SUBSTR(T.CDCHAVEREG,5,10)
                    AND T.CDREGISTRO = '433'
                 UNION ALL
                 SELECT DTEMISSAO
                   FROM NOTAFISCAL N, TMP_REGDADOS_IN86 T
                  WHERE N.CDFILIAL = SUBSTR(T.CDCHAVEREG,1,4)
                    AND N.NRLANCTONF = SUBSTR(T.CDCHAVEREG,5,10)
                    AND T.CDREGISTRO = '435'
                 UNION ALL
                 SELECT DTEMISSAO
                   FROM NOTAFISCAL N, TMP_REGDADOS_IN86 T
                  WHERE N.CDFILIAL = SUBSTR(T.CDCHAVEREG,1,4)
                    AND N.NRLANCTONF = SUBSTR(T.CDCHAVEREG,5,10)
                    AND T.CDREGISTRO = '438');

         V_SEQUNCIAL := NVL(V_SEQUNCIAL,0) +1;
         INSERT INTO ARQMAGNETICO
           (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
           ('06'||LPAD(RTRIM(V_SEQUNCIAL), 8, '0'), V_DATA_ATU||C_NATUOPER.DSARQMAG, P_NRSEQARQMAG);
      END LOOP;
   END LOOP;
END;
/
