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

CREATE FUNCTION VALOR_IMPOSTO_ITEM (@P_CDFILIAL     VARCHAR(04),
                                    @P_NRLANCTONF   VARCHAR(10),
                                    @P_NRSEQITPROD  VARCHAR(04),
                                    @P_CDIMPOSTO    VARCHAR(02),
                                    @P_IDVALOR      VARCHAR(01),
                                    @P_CDFISCAL     VARCHAR(01),
                                    @P_NRITPROIMPOS 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_VALOR DOUBLE PRECISION;


   SELECT @V_VRBASECALCIT = ISNULL(SUM(VRBASECALCIT),0) ,
          @V_VRALIQITEM   = ISNULL(SUM(VRALIQITEM),0)   ,
          @V_VRIMPOSTOIT  = ISNULL(SUM(VRIMPOSTOIT),0)  ,
          @V_VRPERREDBCIT = ISNULL(SUM(VRPERREDBCIT),0)
   FROM ITEMPROIMPOS
   WHERE CDFILIAL     = @P_CDFILIAL     AND
         NRLANCTONF   = @P_NRLANCTONF   AND
         NRSEQITPROD  = @P_NRSEQITPROD  AND
         CDIMPOSTO    = @P_CDIMPOSTO    AND
         NRITPROIMPOS = @P_NRITPROIMPOS 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;
   RETURN(@V_VALOR);
END
GO

-- VERSAO --
EXEC ATUVEROBJ 'VALOR_IMPOSTO_ITEM','5.05.012';
GO

