CREATE OR REPLACE FUNCTION DTPOSICAO_POSESTCONS(P_CDFILIAL     IN FILIAL.CDFILIAL%TYPE,
                                                P_CDPRODUTO    IN PRODUTO.CDPRODUTO%TYPE,
                                                P_DTREFERENCIA IN DATE) RETURN DATE
AS
   V_DTPOSIESTQ    DATE;
BEGIN
   V_DTPOSIESTQ   := NULL;

   SELECT DTPOSESTCON
     INTO V_DTPOSIESTQ
     FROM (SELECT P.DTPOSESTCON
             FROM POSESTCONS P
            WHERE P.CDFILIAL    = P_CDFILIAL
              AND P.CDPRODUTO   = P_CDPRODUTO
              AND P.DTPOSESTCON <= P_DTREFERENCIA
            ORDER BY 1 DESC)
    WHERE ROWNUM = 1;

   RETURN(V_DTPOSIESTQ);
END;
/