IF NOT OBJECT_ID('UFD_EST_PROD_COND_CP_PG_FORN_VIGENTE_PW') IS NULL
	BEGIN 
		DROP FUNCTION UFD_EST_PROD_COND_CP_PG_FORN_VIGENTE_PW
	END
	
GO	

CREATE FUNCTION UFD_EST_PROD_COND_CP_PG_FORN_VIGENTE_PW(@CD_EMP INT, @CD_PED_CP_PARAM INT, @CD_PROD INT, @CD_ORDEM INT )
RETURNS @RS_RETURN TABLE(	CD_EMP					INT, 
							CD_ORD_MCP_PW			INT,							
							CD_PROD					INT,
							CD_FORN					INT,
							CD_PED_CP_PARAM			INT)
AS
	BEGIN
		DECLARE @RS_RETURN_TMP TABLE(	CD_EMP					INT, 
										CD_ORD_MCP_PW			INT,							
										CD_PROD					INT,
										CD_FORN					INT,
										CD_PED_CP_PARAM			INT)
							
		INSERT INTO @RS_RETURN_TMP
			SELECT 
				MCP.CD_EMP,
				ROW_NUMBER() OVER (PARTITION BY   MCP.CD_PROD   ORDER BY MCP.CD_PROD, MCP.CD_ORDEM) AS CD_ORD_MCP_PW, 			
				MCP.CD_PROD,
				MCP.CD_FORN,
				@CD_PED_CP_PARAM AS CD_PED_CP_PARAM
			FROM V_EST_PROD_COND_CP_PG_FORN_VIGENTE MCP 
				INNER JOIN EST_PED_CP_PARAM_PG_FORN_INTEGRACAO PARAM_FORN ON 
					MCP.CD_EMP = PARAM_FORN.CD_EMP
					AND MCP.CD_FORN = PARAM_FORN.CD_FORN
			WHERE 
				PARAM_FORN.CD_EMP = @CD_EMP
				AND PARAM_FORN.CD_PED_CP_PARAM = @CD_PED_CP_PARAM
				AND MCP.CD_PROD = @CD_PROD
		
		INSERT INTO @RS_RETURN
			SELECT 
				CD_EMP,
				CD_ORD_MCP_PW,
				CD_PROD,	
				CD_FORN,	
				CD_PED_CP_PARAM	
			FROM 
				@RS_RETURN_TMP
			WHERE 
				CD_ORD_MCP_PW = @CD_ORDEM
				
		RETURN
			
	END