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

CREATE FUNCTION VALOR_IMPOSTO_NF(
                @P_CDFILIAL    VARCHAR(04),
                @P_NRLANCTONF  VARCHAR(10),
                @P_CDIMPOSTO   VARCHAR(02),
                @P_IDVALOR     VARCHAR(04),
                @P_CDFISCAL    VARCHAR(01))
RETURNS NUMERIC
AS
BEGIN
   DECLARE @V_VRBASECALCIT DOUBLE PRECISION;
   DECLARE @V_VRALIQITEM   DOUBLE PRECISION;
   DECLARE @V_VRIMPOSTOIT  DOUBLE PRECISION;
   DECLARE @V_VRPERREDBCIT DOUBLE PRECISION;
   DECLARE @V_VRCONTITIMPO DOUBLE PRECISION;
   DECLARE @V_VALOR DOUBLE PRECISION;

   SELECT @V_VRBASECALCIT = ISNULL(SUM(VRBASECALCIT),0),
          @V_VRALIQITEM = ISNULL(MAX(VRALIQITEM),0),
          @V_VRIMPOSTOIT = ISNULL(SUM(VRIMPOSTOIT),0),
          @V_VRPERREDBCIT = ISNULL(MAX(VRPERREDBCIT),0),
          @V_VRCONTITIMPO = ISNULL(MAX(VRCONTITIMP),0)
   FROM ITEMPROIMPOS
   WHERE (CDFILIAL     = @P_CDFILIAL)    AND
         (NRLANCTONF   = @P_NRLANCTONF)  AND
         (CDIMPOSTO    BETWEEN @P_CDIMPOSTO AND @P_CDIMPOSTO) AND
         (NRITPROIMPOS = '1')           AND
         (CDFISCALIT = ISNULL(@P_CDFISCAL, CDFISCALIT));

   IF @P_IDVALOR = 'A' BEGIN
      RETURN(@V_VRALIQITEM);
      SET @V_VALOR = @V_VRALIQITEM;
   END
   IF @P_IDVALOR = 'B' BEGIN
      RETURN(@V_VRBASECALCIT);
      SET @V_VALOR = @V_VRBASECALCIT;
   END;
   IF @P_IDVALOR = 'I' BEGIN
      RETURN(@V_VRIMPOSTOIT);
      SET @V_VALOR = @V_VRIMPOSTOIT;
   END;
   IF @P_IDVALOR = 'P' BEGIN
      RETURN(@V_VRPERREDBCIT);
      SET @V_VALOR = @V_VRPERREDBCIT;
   END;
   IF @P_IDVALOR = 'C' BEGIN
      RETURN(@V_VRCONTITIMPO);
      SET @V_VALOR = @V_VRCONTITIMPO;
   END;
   RETURN(@V_VALOR);
END
GO

-- VERSAO --
EXEC ATUVEROBJ 'VALOR_IMPOSTO_NF','5.05.025';
GO

