CREATE OR REPLACE FUNCTION GIAM_TO_SEGMENTO_J(
   P_DTINICIO      IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFIM         IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_CDEMPRESA     IN MAPAAPURAC.CDEMPRESA%TYPE,
   P_CDINSCESTA    IN MAPAAPURAC.CDINSCESTA%TYPE,
   P_NRSEQARQMAG   IN ARQMAGNETICO.NRSEQARQMAG%TYPE,
   P_IDRETIFIC     IN NOTAFISCAL.CDTIPOOPER%TYPE,
   P_NRTARE        IN VARCHAR2,
   P_DTVENCTARE    IN NOTAFISCAL.DTENTRSAID%TYPE) RETURN NUMBER
AS
   V_CONTREG NUMBER;
BEGIN
   FOR C_REG_J IN (SELECT 'J'                               ||
                          RPAD(CDINSCESTA,11,'0')           ||
                          TO_CHAR(DTFIMPERIODO,'MMYYYY')    ||
                          P_IDRETIFIC                       ||
                          P_NRTARE                          ||
                          TO_CHAR(P_DTVENCTARE,'DDMMYYYY')  AS SEG_J
                     FROM MAPAAPURAC M
                    WHERE M.CDEMPRESA    = P_CDEMPRESA
                      AND M.CDINSCESTA   = P_CDINSCESTA
                      AND M.DTINIPERIODO = P_DTINICIO
                      AND M.DTFIMPERIODO = P_DTFIM
                      AND M.CDIMPOSTO    = '00') LOOP

      V_CONTREG := NVL(V_CONTREG,0) + 1;

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         ('10'||LPAD(RTRIM(V_CONTREG), 8, '0'), C_REG_J.SEG_J, P_NRSEQARQMAG);

   END LOOP;
   RETURN(NVL(V_CONTREG,0));
END;
/