IF EXISTS (SELECT * FROM SYSOBJECTS O, SYSUSERS U
           WHERE O.NAME = 'CALC_ESTOQ_CONS' AND
                 TYPE = 'FN' 		       AND
	              U.UID = O.UID            AND
	              U.NAME = USER)
DROP FUNCTION CALC_ESTOQ_CONS
GO
CREATE FUNCTION CALC_ESTOQ_CONS(
   @P_CDFILIAL     VARCHAR(4),
   @P_CDPRODUTO    VARCHAR(10),
   @P_DTREFERENCIA DATETIME) RETURNS DOUBLE PRECISION
AS
BEGIN
   DECLARE @V_QTESTOQUE     DOUBLE PRECISION;

   SET @V_QTESTOQUE = 0;

   SELECT
      @V_QTESTOQUE = ISNULL(MAX(P.QTESTDIACON), 0)      
   FROM
      POSESTCONS P
   WHERE
      P.CDFILIAL    = @P_CDFILIAL  AND
      P.CDPRODUTO   = @P_CDPRODUTO AND
      P.DTPOSESTCON = (SELECT
                           MAX(DTPOSESTCON)
                        FROM POSESTCONS
                        WHERE
                           POSESTCONS.CDFILIAL  = P.CDFILIAL  AND
                           POSESTCONS.CDPRODUTO = P.CDPRODUTO AND
                           POSESTCONS.DTPOSESTCON <= @P_DTREFERENCIA);
   RETURN(@V_QTESTOQUE);
END
GO


-- VERSAO --
EXEC ATUVEROBJ 'CALC_ESTOQ_CONS','4.09.090';
GO

