CREATE OR REPLACE FUNCTION ARQUIVO_11_GIM_PB(
   P_CDEMPRESA    IN EMPRESA.CDEMPRESA%TYPE,
   P_CDINSCESTA   IN EMPRESA.CDINSCESTA%TYPE,
   P_CDINSCESTAST IN NOTAFISCAL.CDINSCESTAST%TYPE,
   P_SEQMAGNET    IN VARCHAR,
   P_CONTADOR     IN NUMBER) RETURN VARCHAR
AS
   V_CONTADOR NUMBER;
BEGIN
   V_CONTADOR   := P_CONTADOR;
   FOR C_REGISTRO11 IN (SELECT SUBSTR(
                           '11'||
                           RPAD(NVL(ST.DSENDEIEST,IE.DSENDEIEST),34,' ')||
                           RPAD('00000s/n',27,' ')||
                           RPAD(NVL(ST.NMBAIRIEST,IE.NMBAIRIEST),15,' ')||
                           LPAD(REPLACE(REPLACE(NVL(ST.NRCEPIEST,IE.NRCEPIEST),'.',''),'-',''),8,'0')||
                           RPAD(NVL(NVL(ST.NMREPRINSEST,IE.NMREPRINSEST), ' '),28,' ')||
                           LPAD(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(NVL(NVL(ST.NRTELEIEST,IE.NRTELEIEST),'0'),' ',''),')',''),'(',''),'-',''),'.',''),12,'0')
                           ,1,126) AS DSARQMAG
                        FROM INSCRESTAD IE, (SELECT I.CDEMPRESA, I.CDINSCESTA, I.DSENDEIEST, I.NMBAIRIEST,
                                                    I.NRCEPIEST, I.NMREPRINSEST, I.NRTELEIEST
                                                 FROM INSCRESTADST I
                                                WHERE I.CDEMPRESA    = P_CDEMPRESA
                                                  AND I.CDINSCESTA   = P_CDINSCESTA
                                                  AND I.CDINSCESTAST = P_CDINSCESTAST) ST
                        WHERE IE.CDEMPRESA   = P_CDEMPRESA   AND
                              IE.CDINSCESTA  = P_CDINSCESTA  AND
                              IE.CDEMPRESA  = ST.CDEMPRESA(+) AND
                              IE.CDINSCESTA = ST.CDINSCESTA(+)) LOOP

      V_CONTADOR := NVL(V_CONTADOR,0) + 1;
      INSERT INTO ARQMAGNETICO
        (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('11'||LPAD(V_CONTADOR, 8, '0'), C_REGISTRO11.DSARQMAG, P_SEQMAGNET);
   END LOOP;
   RETURN (V_CONTADOR);
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('ARQUIVO_11_GIM_PB','6.39.013'); END;
/

