IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UFD_BUSCA_PRECO_PRODUTO_TRANSFERENCIA]') 
			AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[UFD_BUSCA_PRECO_PRODUTO_TRANSFERENCIA]
GO
  
CREATE FUNCTION [dbo].[UFD_BUSCA_PRECO_PRODUTO_TRANSFERENCIA](@CD_EMP	 INT
													,@CD_FILIAL  INT
													,@CD_PROD	 INT
													,@TIPO_PRECO INT
													) 
RETURNS MONEY WITH ENCRYPTION AS
BEGIN


	/*FARMAGOI-46713*/
	
	DECLARE @VLR_PROD	MONEY 

	set @VLR_PROD = 0;


	IF (@TIPO_PRECO =1 )
		begin 
			SET @VLR_PROD = ISNULL((SELECT EST_PROD_CPL.VLR_CUSTO_MD
									FROM EST_PROD_CPL
									WHERE CD_PROD = @CD_PROD
									AND CD_FILIAL = @CD_FILIAL),@VLR_PROD);
		end
		
	IF (@TIPO_PRECO =2 )
		begin 
			SET @VLR_PROD = ISNULL((SELECT EST_PROD_CPL.VLR_CUSTO
									FROM EST_PROD_CPL
									WHERE CD_PROD = @CD_PROD
									AND CD_FILIAL = @CD_FILIAL),@VLR_PROD);
		end
		
		
	IF (@TIPO_PRECO =4 )
		begin 
			SET @VLR_PROD = ISNULL((SELECT TOP 1 V.VLR_FORN
									FROM V_EST_PROD_PRECO_TBL V
									WHERE CD_PROD = @CD_PROD
									AND CD_FILIAL = @CD_FILIAL
									ORDER BY DT_CAD DESC),@VLR_PROD);
		end
		
	IF (@TIPO_PRECO =5 )
		begin 
			SET @VLR_PROD = ISNULL((SELECT TOP 1 EST_PROD_PRECO.VLR_TABELA
									FROM EST_PROD_PRECO
									WHERE CD_PROD = @CD_PROD
									AND CD_FILIAL = @CD_FILIAL
									ORDER BY DT_CAD DESC),@VLR_PROD);
		end
		
	IF (@TIPO_PRECO =6 )
		begin 
			SET @VLR_PROD = ISNULL((SELECT TOP 1 V.VLR_VD
									FROM V_EST_PROD_PRECO_TBL V
									WHERE CD_PROD = @CD_PROD
									AND CD_FILIAL = @CD_FILIAL
									ORDER BY DT_CAD DESC),@VLR_PROD);
		end


	RETURN (ISNULL(@VLR_PROD,0))

end

 