CREATE OR REPLACE PROCEDURE DASHBOARD_FIN_SALDO_CONTAS (   
    P_DTSALDO IN DATE DEFAULT SYSDATE
) AS

BEGIN

DELETE FROM PDCSALDO;

FOR C_SALDO IN (
    SELECT
        *
    FROM
        (
            SELECT
                CC.NRORG,
                BC.CDBANCO,
                BC.NMBANCO,
                BC.CDPICTCONT,
                BC.CDPICTAGEN,
                CC.CDCONTCORR,
                CC.DSCONTCORR,
                EM.CDEMPRESA,
                EM.NMEMPRESA,
                CC.CDREDUCONT,
                CC.VRLIMITCREDCCOR,
                AG.CDAGENCIA,
                AG.NMAGENCIA,
                '' AS CDCONTCORRMASK,
                '' AS CDAGENCIAMASK,
                NVL(SALDO_CONTACORR(CC.CDREDUCONT,P_DTSALDO),0) AS VRSALDO,
                NVL(SALDO_CONTACORR(CC.CDREDUCONT,P_DTSALDO),0) AS VRSALDOCLIM,
                TO_CHAR(P_DTSALDO,'DD/MM/YYYY')  DTSALDO
            FROM
                CONTCORR CC,
                BANCO BC,
                EMPRESA EM,
                AGENCIA AG
            WHERE
                ( BC.CDBANCO = AG.CDBANCO )
                AND ( AG.CDBANCO = CC.CDBANCO )
                AND ( CC.CDAGENCIA = AG.CDAGENCIA )
                AND ( CC.CDEMPRESA = EM.CDEMPRESA )
            ORDER BY
                CC.CDEMPRESA,
                CC.CDBANCO,
                CC.CDREDUCONT
        )
    WHERE
        VRSALDO <> '0'
) LOOP
   
   INSERT
    INTO PDCSALDO(
        NRORG,
        CDBANCO,
        NMBANCO,
        CDPICTCONT,
        CDPICTAGEN,
        CDCONTCORR,
        DSCONTCORR,
        CDEMPRESA,
        NMEMPRESA,
        CDREDUCONT,
        VRLIMITCREDCCOR,
        CDAGENCIA,
        NMAGENCIA,
        CDCONTCORRMASK,
        CDAGENCIAMASK,
        VRSALDO,
        VRSALDOCLIM,
        DTSALDO
    )
VALUES
    ( C_SALDO.NRORG, C_SALDO.CDBANCO, C_SALDO.NMBANCO, C_SALDO.CDPICTCONT, C_SALDO.CDPICTAGEN, C_SALDO.CDCONTCORR, 
        C_SALDO.DSCONTCORR, C_SALDO.CDEMPRESA, C_SALDO.NMEMPRESA, C_SALDO.CDREDUCONT, C_SALDO.VRLIMITCREDCCOR, 
        C_SALDO.CDAGENCIA, C_SALDO.NMAGENCIA, C_SALDO.CDCONTCORRMASK, C_SALDO.CDAGENCIAMASK, C_SALDO.VRSALDO,
        C_SALDO.VRSALDOCLIM, C_SALDO.DTSALDO);
        
    END LOOP;

END;
/