
/****** Object:  UserDefinedFunction [dbo].[UFD_EST_ARV_MD_F_GRP_PARAM_CURVA_AVALIACAO]    Script Date: 17/05/2018 17:23:48 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UFD_EST_ARV_MD_F_GRP_PARAM_CURVA_AVALIACAO]') )
DROP FUNCTION [dbo].[UFD_EST_ARV_MD_F_GRP_PARAM_CURVA_AVALIACAO];
GO

/****** Object:  UserDefinedFunction [dbo].[UFD_EST_ARV_MD_F_GRP_PARAM_CURVA_AVALIACAO]    Script Date: 17/05/2018 17:23:48 ******/

SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

--SELECT DBO.UFD_EST_ARV_MD_F_GRP_PARAM_CURVA_AVALIACAO(1,5,10,1)
CREATE FUNCTION [dbo].[UFD_EST_ARV_MD_F_GRP_PARAM_CURVA_AVALIACAO] (@CD_EMP        INT
																	, @CD_FILIAL     INT
																	, @VLR_PARAMETRO MONEY
																	, @CD_PROD      INT
																	)

RETURNS INT
AS
BEGIN
	DECLARE @CD_CURVA INT;

	SET @CD_CURVA = ISNULL(( SELECT TOP 1 CD_SIGLA
							FROM V_EST_ARV_MD_F_GRP_PARAM_CURVA_PRC_FILIAL
							WHERE  
								CD_EMP = @CD_EMP
								AND VLR_PARAMETRO <= @VLR_PARAMETRO
								AND CD_FILIAL = @CD_FILIAL
								AND CD_PROD = @CD_PROD
							ORDER BY VLR_PARAMETRO DESC), 0);

	if @CD_CURVA =0
		SET @CD_CURVA =( SELECT CD_CURVA_PD FROM PRC_EMP WHERE  CD_EMP = @CD_EMP);

	RETURN @CD_CURVA;
END;
GO


