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

CREATE FUNCTION VALOR_CARGA_TRIBUTARIA(@P_CDIMPOSTO    VARCHAR(02),
                                       @P_CDFILIAL     VARCHAR(04),
                                       @P_NRLANCTONF   VARCHAR(10))
RETURNS NUMERIC
AS
BEGIN
   DECLARE @V_CDIMPCARGATRIB    VARCHAR(02);
   DECLARE @V_VRCARGTRIBUT      DOUBLE PRECISION;

   SET @V_VRCARGTRIBUT = 0;

   SELECT @V_CDIMPCARGATRIB = CDIMPCARGATRIB
   FROM IMPOSTO
   WHERE CDIMPOSTO = @P_CDIMPOSTO;

   SELECT @V_VRCARGTRIBUT = ROUND(SUM(I.VRIMPOSTOIT),2)
   FROM (SELECT IT.CDIMPOSTO, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, CDFISCALIT,
                CDSITUTRIBIT, CDFISCOPERIT, CDSUFXCFOPIT, IDTRIMPSTII, SUM(VRCONTITIMP) AS VRCONTITIMP,
                SUM(VRBASECALCIT) AS VRBASECALCIT, SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                MAX(NRITPROIMPOS) AS NRITPROIMPOS
         FROM ITEMPROIMPOS IT, IMPOSTO I
         WHERE CDFILIAL     = @P_CDFILIAL
           AND NRLANCTONF   = @P_NRLANCTONF
           AND IT.CDIMPOSTO = @V_CDIMPCARGATRIB
           AND IT.CDIMPOSTO = I.CDIMPOSTO
           AND IT.NRITPROIMPOS = '1'
           AND IT.CDFISCALIT   = '1'
         GROUP BY IT.CDIMPOSTO, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, CDFISCALIT,
                  CDSITUTRIBIT, CDFISCOPERIT, CDSUFXCFOPIT, IDTRIMPSTII) I;

   RETURN(@V_VRCARGTRIBUT);
END
GO

-- VERSAO --
EXEC ATUVEROBJ 'VALOR_CARGA_TRIBUTARIA','5.05.059';
GO

