CREATE OR REPLACE FUNCTION GIA_PE_ANUAL_1(
   P_CONTREG         IN NUMBER,
   P_CDINSCESTA      IN INSCRESTAD.CDINSCESTA%TYPE,
   P_ANO             IN VARCHAR2,
   P_INDICADOR       IN VARCHAR2,
   P_NRSEQARQMAG     IN ARQMAGNETICO.NRSEQARQMAG%TYPE) RETURN NUMBER
AS
   V_CONTREG  NUMBER;
BEGIN
   V_CONTREG := NVL(P_CONTREG,0);

   FOR C_REG_1 IN (SELECT LPAD(V_CONTREG,6,'0')                               ||
                          '1'                                                 ||
                          '000000'                                            ||
                          RPAD(P_CDINSCESTA,14,' ')                           ||
                          LPAD(REPLACE(REPLACE(NRINSJURIEST,'/'),'-'),14,'0') ||
                          P_ANO                                               ||
                          DECODE(P_INDICADOR,'O','N','S')                     ||
                          RPAD(E.NMRAZSOCEMPR,46,' ')                         ||
                          RPAD(C.NRCPFRESPONS,11,' ')                         ||
                          RPAD(C.NMCONTADOR,40,' ')                           ||
                          LPAD(REPLACE(REPLACE(REPLACE(IE.NRTELEIEST,'('),'-'),')'),14,'0') ||
                          RPAD(E.DSEMAILEMPRESA,40)  AS DSARQMAG
                     FROM INSCRESTAD IE, CONTADOR C, EMPRESA E
                    WHERE IE.CDINSCESTA  = P_CDINSCESTA
                      AND IE.CDCONTADOR2 = C.CDCONTADOR2
                      AND IE.CDEMPRESA   = E.CDEMPRESA) LOOP

     INSERT INTO ARQMAGNETICO
        (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
     VALUES
        (LPAD(RTRIM(V_CONTREG), 10, '0'), C_REG_1.DSARQMAG, P_NRSEQARQMAG);

     V_CONTREG := NVL(V_CONTREG,0) + 1;
  END LOOP;
  
  RETURN V_CONTREG;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('GIA_PE_ANUAL_1','6.39.005'); END;
/
