create or replace FUNCTION SALDO_CONTACORR_MOBILE
   (P_CDREDUCONT IN CONTCORR.CDREDUCONT%TYPE,
    P_DATAREFE   IN NOTAFISCAL.DTEMISSAO%TYPE,
    P_DTINICIAL  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 AND
         VRSDOIMPLA is not null;

 /* if V_DATASALDO is null then
  
    SELECT MAX(DTSDOCCORR)
    INTO V_DATASALDO
    FROM SDOCCORR
   WHERE CDREDUCONT = P_CDREDUCONT AND
         DTSDOCCORR   < P_DATAREFE  and
         VRSDOIMPLA is not null;
  
  end if;*/

  if P_DATAREFE >= V_DATASALDO then 
     SELECT SUM(VRSDOIMPLA)
     INTO V_VRSALDO
     FROM SDOCCORR
     WHERE CDREDUCONT = P_CDREDUCONT AND
           DTSDOCCORR = V_DATASALDO AND
           DTSDOCCORR >= P_DTINICIAL;
  else
    V_VRSALDO := 0;
  end if;
  RETURN (V_VRSALDO);
END;