CREATE OR REPLACE FUNCTION SALDO_CONTACORR
   (P_CDREDUCONT IN CONTCORR.CDREDUCONT%TYPE,
    P_DATAREFE   IN NOTAFISCAL.DTEMISSAO%TYPE,
    P_IDVALOR    IN NOTAFISCAL.IDENTRSAIDOP%TYPE DEFAULT 'S') RETURN NUMBER
AS
   V_DATASALDO NOTAFISCAL.DTEMISSAO%TYPE;
   V_VRSALDO   NOTAFISCAL.VRNOTAFISC%TYPE;
BEGIN

  SELECT MAX(DTSDOCCORR)
  INTO V_DATASALDO
  FROM SDOCCORR
  WHERE CDREDUCONT = P_CDREDUCONT AND
        DTSDOCCORR  < P_DATAREFE;

  IF P_IDVALOR = 'I' THEN
     SELECT SUM(VRSDOIMPLA)
     INTO V_VRSALDO
     FROM SDOCCORR
     WHERE CDREDUCONT = P_CDREDUCONT AND
           DTSDOCCORR = V_DATASALDO;
  ELSE
     SELECT SUM(VRSDOCCORR)
     INTO V_VRSALDO
     FROM SDOCCORR
     WHERE CDREDUCONT = P_CDREDUCONT AND
           DTSDOCCORR = V_DATASALDO;
  END IF;

  RETURN (V_VRSALDO);
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('SALDO_CONTACORR','4.11.176'); END;
/

