CREATE OR REPLACE FUNCTION VALOR_ENCARGO_AF
   (P_CDFILDEST   IN AUTOFORNE.CDFILDEST%TYPE,
    P_CDFILLANC   IN AUTOFORNE.CDFILLANC%TYPE,
    P_NRAUTOFORN  IN AUTOFORNE.NRAUTOFORN%TYPE,
    P_DTPROGENTAF IN ITEMAUTF.DTPROGENTAF%TYPE) RETURN FLOAT
AS
   V_VRENCARGOAF FLOAT;
BEGIN

   SELECT SUM(DECODE(E.IDENCARGO, 'A', VRENCARGOAF, (VRENCARGOAF * -1)))
   INTO V_VRENCARGOAF
   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;
/
