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

CREATE FUNCTION VALOR_IMPOSTO_ITEM_NFE
  (@P_CDFILIAL     VARCHAR(4),
   @P_NRLANCTONF   VARCHAR(10),
   @P_NRSEQITPROD  VARCHAR(4),
   @P_CDIMPOSTO    VARCHAR(2),
   @P_IDVALOR      VARCHAR(1),
   @P_CDFISCAL     VARCHAR(1),
   @P_NRITPROIMPOS VARCHAR(1) = '1')
   RETURNS DOUBLE PRECISION
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(I.VRBASECALCIT),0),
          @V_VRALIQITEM   = ISNULL(MAX(I.VRALIQITEM),0),
          @V_VRIMPOSTOIT  = ISNULL(SUM(I.VRIMPOSTOIT),0),
          @V_VRPERREDBCIT = ISNULL(SUM(I.VRPERREDBCIT),0),
          @V_VRCONTITIMPO = ISNULL(SUM(I.VRCONTITIMP),0)
     FROM ITEMPROIMPOS I, IMPOSTO P
    WHERE I.CDFILIAL     = @P_CDFILIAL     AND
          I.NRLANCTONF   = @P_NRLANCTONF   AND
          I.NRSEQITPROD  = @P_NRSEQITPROD  AND
          I.CDIMPOSTO    = P.CDIMPOSTO    AND
          P.CDIMPOSTONFE = @P_CDIMPOSTO    AND
          I.NRITPROIMPOS = @P_NRITPROIMPOS AND
          I.CDFISCALIT   = ISNULL(@P_CDFISCAL, I.CDFISCALIT);
   IF @P_IDVALOR = 'A' BEGIN
      SET @V_VALOR = @V_VRALIQITEM;
   END
   ELSE BEGIN
      IF @P_IDVALOR = 'B' BEGIN
         SET @V_VALOR = @V_VRBASECALCIT;
      END
      ELSE BEGIN
         IF @P_IDVALOR = 'I' BEGIN
            SET @V_VALOR = @V_VRIMPOSTOIT;
         END
         ELSE BEGIN
            IF @P_IDVALOR = 'P' BEGIN
               SET @V_VALOR = @V_VRPERREDBCIT;
            END
            ELSE BEGIN
               IF @P_IDVALOR = 'C' BEGIN
                  SET @V_VALOR = @V_VRCONTITIMPO;
               END;
            END;
         END;
      END;
   END;
   RETURN(@V_VALOR);
END;
GO

-- VERSAO --
EXEC ATUVEROBJ 'VALOR_IMPOSTO_ITEM_NFE','5.00.000';
GO

