IF EXISTS (SELECT *
           FROM SYSOBJECTS O, SYSUSERS U
           WHERE O.NAME = 'VALOR_ENCARGO_AF' AND
                 TYPE = 'FN' AND
                 U.UID = O.UID  AND
                 U.NAME = USER)
DROP FUNCTION VALOR_ENCARGO_AF
GO

CREATE FUNCTION VALOR_ENCARGO_AF
   (@P_CDFILDEST   VARCHAR(04),
    @P_CDFILLANC   VARCHAR(04),
    @P_NRAUTOFORN  VARCHAR(10),
    @P_DTPROGENTAF DATETIME) RETURNS FLOAT
AS
BEGIN
   DECLARE @V_VRENCARGOAF DOUBLE PRECISION;

   SET @V_VRENCARGOAF = 0;

   SELECT @V_VRENCARGOAF = SUM(CASE E.IDENCARGO
                                  WHEN 'A' THEN VRENCARGOAF
                                  ELSE (VRENCARGOAF * -1)
                               END)
   FROM ENCARGOAF A, ENCARGO E
   WHERE A.CDFILDEST   = @P_CDFILDEST    AND
         A.CDFILLANC   = @P_CDFILLANC    AND
         A.NRAUTOFORN  = @P_NRAUTOFORN   AND
         A.DTENTRENCAF = @P_DTPROGENTAF  AND
         A.CDENCARGO   = E.CDENCARGO     AND
         E.IDENCARGO   IN ('A', 'D')     AND
         A.VRENCARGOAF > 0 ;

   RETURN(@V_VRENCARGOAF);
END
GO

-- VERSAO --
EXEC ATUVEROBJ 'VALOR_ENCARGO_AF','4.05.126';
GO

