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

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

   SET @V_VRIMPITMAF = 0;

   SELECT @V_VRIMPITMAF = SUM(CASE IP.IDTRATIMPO
                                  WHEN 'A' THEN VRIMPITMAF
                                  ELSE (VRIMPITMAF * -1)
                               END)
   FROM IMPITMAF I, IMPOSTO IP
   WHERE (CDFILDEST   = @P_CDFILDEST)   AND
         (CDFILLANC   = @P_CDFILLANC)   AND
         (NRAUTOFORN  = @P_NRAUTOFORN)  AND
         (DTPROGENTAF = @P_DTPROGENTAF) AND
         (IDTRATIMPO IN ('A', 'D'))     AND
         (I.CDIMPOSTO = IP.CDIMPOSTO)   AND
         ISNULL(IP.IDACRPRODENTRNF, 'N') = 'N';

   RETURN(@V_VRIMPITMAF);
END
GO


-- VERSAO --
EXEC ATUVEROBJ 'VALOR_IMPOSTO_AF','5.05.022';
GO

