CREATE OR REPLACE FUNCTION SF_CALC_ESTOQ_CONS(
   P_CDFILIAL     IN FILIAL.CDFILIAL%TYPE,
   P_CDPRODUTO    IN PRODUTO.CDPRODUTO%TYPE,
   P_DTREFERENCIA IN DATE,
   P_NRORG        IN POSESTCONS.NRORG%TYPE DEFAULT 1) RETURN NUMBER IS
   V_QTESTOQUE  NUMBER;
BEGIN
   SELECT
      NVL(MAX(P.QTESTDIACON), 0)
   INTO
      V_QTESTOQUE
   FROM
      POSESTCONS P
   WHERE
      P.CDFILIAL    = P_CDFILIAL  AND
      P.CDPRODUTO   = P_CDPRODUTO AND
      P.NRORG       = P_NRORG     AND
      P.DTPOSESTCON = (SELECT
                           MAX(POSESTCONS.DTPOSESTCON)
                        FROM POSESTCONS
                        WHERE
                           POSESTCONS.CDFILIAL     = P.CDFILIAL  AND
                           POSESTCONS.CDPRODUTO    = P.CDPRODUTO AND
                           POSESTCONS.NRORG        = P_NRORG     AND
                           POSESTCONS.DTPOSESTCON <= P_DTREFERENCIA);
   RETURN(V_QTESTOQUE);
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('SF_CALC_ESTOQ_CONS','4.07.016'); END;
/

