IF EXISTS (SELECT * FROM SYSOBJECTS O, SYSUSERS U
           WHERE O.NAME = 'VALOR_PEDIDO' AND
                 TYPE = 'FN' 		       AND
	              U.UID = O.UID            AND
	              U.NAME = USER)
DROP FUNCTION VALOR_PEDIDO
GO
CREATE FUNCTION VALOR_PEDIDO(
   @P_CDFILIAL     VARCHAR(4),
   @P_NRPEDIDO    VARCHAR(10)) RETURNS NUMERIC(10,5)
AS
BEGIN
   DECLARE @V_VRPEDIDO DOUBLE PRECISION;
   DECLARE @V_VRITEM DOUBLE PRECISION;
   DECLARE @V_VRENCARGO DOUBLE PRECISION;
   DECLARE @V_VRIMPOSTO DOUBLE PRECISION;

   SET @V_VRPEDIDO = 0;

   SELECT @V_VRITEM = ISNULL(SUM((I.QTITEMPED * I.VRPREUNITPED) - (ISNULL(I.VRDESITPED,0))),0)
     FROM ITEMPEDIDO I
    WHERE I.CDFILIAL = @P_CDFILIAL
      AND I.NRPEDIDO = @P_NRPEDIDO
      AND ISNULL(I.IDPRODBONIF, 'N') = 'N';

   SELECT @V_VRENCARGO = ISNULL(SUM(CASE EN.IDENCARGO WHEN 'A' THEN ISNULL(E.VRENCARGOPED,0)
                                                      WHEN 'D' THEN (ISNULL(E.VRENCARGOPED,0) * -1)
                                                      ELSE 0 END),0)
     FROM ENCARGOPED E, ENCARGO EN
    WHERE E.CDENCARGO = EN.CDENCARGO
      AND E.CDFILIAL = @P_CDFILIAL
      AND E.NRPEDIDO = @P_NRPEDIDO;

   SELECT @V_VRIMPOSTO = ISNULL(SUM(CASE IM.IDTRATIMPO WHEN 'A' THEN ISNULL(IP.VRIMPOSTOITPED,0)
                                                       WHEN 'D' THEN (ISNULL(IP.VRIMPOSTOITPED,0) * -1)
                                                       ELSE 0 END),0)
     FROM IMPOSTO IM, IMPITEMPEDIDO IP, ITEMPEDIDO IT
    WHERE IT.CDFILIAL = @P_CDFILIAL
      AND IT.NRPEDIDO = @P_NRPEDIDO
      AND ISNULL(IT.IDPRODBONIF, 'N') = 'N'
      AND IT.CDFILIAL = IP.CDFILIAL
      AND IT.NRPEDIDO = IP.NRPEDIDO
      AND IT.NRITEMPED = IP.NRITEMPED
      AND IP.CDIMPOSTO = IM.CDIMPOSTO;

   SET @V_VRPEDIDO = @V_VRITEM + @V_VRENCARGO + @V_VRIMPOSTO;

   RETURN(@V_VRPEDIDO);
END
GO

-- VERSAO --
EXEC ATUVEROBJ 'VALOR_PEDIDO','6.39.005';
GO
