CREATE OR REPLACE FUNCTION ARQUIVO_DCTF_T9 (
   P_CDEMPRESA           IN EMPRESA.CDEMPRESA%TYPE,
   P_DTINICIAL           IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFINAL             IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_NRSEQARQMAG         IN ARQMAGNETICO.NRSEQARQMAG%TYPE,
   P_SITUACAO            IN NOTAFISCAL.IDSTATUS%TYPE,
   V_TOTREG_R01_R02_R03  NUMBER,
   V_TOTREGAR10          NUMBER,
   V_TOTREGAR11          NUMBER,
   V_TOTREGAR15          NUMBER,
   V_TOTREGAR20          NUMBER) RETURN NUMBER
AS
   V_CONTTOTREG   NUMBER;
   V_REG_T9       VARCHAR2(500);
BEGIN
   V_CONTTOTREG := NVL(V_TOTREG_R01_R02_R03,0)+NVL(V_TOTREGAR10,0)+NVL(V_TOTREGAR11,0)+NVL(V_TOTREGAR15,0)+NVL(V_TOTREGAR20,0);
   V_CONTTOTREG := NVL(V_CONTTOTREG,0) + 1;

   SELECT ('T9'                                                                                      ||
          LPAD(REPLACE(REPLACE(REPLACE(REPLACE(NRINSJUREMPR,'.',''),'-',''),'/',''),' ',''),14,0)    ||
          TO_CHAR(P_DTINICIAL,'YYYYMM')                                                              ||
          P_SITUACAO                                                                                 ||
          DECODE(P_SITUACAO,'0','00000000', TO_CHAR(P_DTINICIAL,'DDMMYYYY'))                         ||
          LPAD(V_CONTTOTREG,'5','0')                                                                 ||
          RPAD(' ',56,' ')                                                                           ||
          RPAD(' ',10,' '))
     INTO V_REG_T9
     FROM EMPRESA
    WHERE CDEMPRESA = P_CDEMPRESA;

   INSERT INTO ARQMAGNETICO
      (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
      ('50'||LPAD(RTRIM(V_CONTTOTREG), 8, '0'), V_REG_T9, P_NRSEQARQMAG);

  RETURN V_CONTTOTREG;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('ARQUIVO_DCTF_T9','5.03.034'); END;
/