IF NOT OBJECT_ID('P_EST_PROD_CPL_MEDIAP_AGENDA') IS NULL
	BEGIN 
		DROP PROCEDURE P_EST_PROD_CPL_MEDIAP_AGENDA
	END

GO

CREATE PROCEDURE P_EST_PROD_CPL_MEDIAP_AGENDA(@CD_EMP INT = 1)
AS
BEGIN
	DECLARE @RS_CD_EMP				INT
	DECLARE @RS_CD_FILIAL			INT
	DECLARE @RS_CD_PROD				INT
	DECLARE @RS_QTDE_MEDIAP			MONEY
	DECLARE @RS_CD_USU				INT
	DECLARE @RS_CD_ARV_MERC_LINHA	INT
	
	DECLARE RS_MEDIAP CURSOR FAST_FORWARD FOR 
		SELECT  
			AGD.CD_EMP, AGD_PROD.CD_FILIAL, AGD_PROD.CD_PROD, AGD_PROD.QTDE_MEDIAP, AGD.CD_USU, A.CD_ARV_MERC_LINHA
		FROM EST_PROD_CPL_MEDIAP_AGENDA AGD
			INNER JOIN EST_PROD_CPL_MEDIAP_AGENDA_EST_PROD AGD_PROD ON 
				AGD.CD_EMP = AGD_PROD.CD_EMP
				AND AGD.CD_AGD_MEDIAP = AGD_PROD.CD_AGD_MEDIAP 		
			INNER JOIN EST_PROD_EST_ARV_MERCADOLOGICA A ON 
				A.CD_EMP = AGD_PROD.CD_EMP
				AND A.CD_PROD = AGD_PROD.CD_PROD
		WHERE 
			AGD.CD_EMP = @CD_EMP
			AND AGD.STS_AGD_MEDIAP = 0
			AND AGD.DT_AGD_MEDIAP <= CONVERT(VARCHAR(10),GETDATE(), 101)
			
	OPEN RS_MEDIAP
	FETCH NEXT FROM RS_MEDIAP INTO @RS_CD_EMP,@RS_CD_FILIAL,@RS_CD_PROD,@RS_QTDE_MEDIAP,@RS_CD_USU,@RS_CD_ARV_MERC_LINHA
		WHILE @@FETCH_STATUS=0
			BEGIN			    
				EXEC P_EST_PROD_CPL_MEDIAP_MANUTENCAO @RS_CD_EMP,@RS_CD_FILIAL,@RS_CD_PROD,@RS_QTDE_MEDIAP,@RS_CD_USU,@RS_CD_ARV_MERC_LINHA				
				
				FETCH NEXT FROM RS_MEDIAP INTO @RS_CD_EMP,@RS_CD_FILIAL,@RS_CD_PROD,@RS_QTDE_MEDIAP,@RS_CD_USU,@RS_CD_ARV_MERC_LINHA
			END
			
	CLOSE RS_MEDIAP;
	DEALLOCATE RS_MEDIAP;	
		
	UPDATE AGD SET 
		STS_AGD_MEDIAP = 1
	FROM EST_PROD_CPL_MEDIAP_AGENDA AGD		
	WHERE 
		AGD.CD_EMP = @CD_EMP
		AND AGD.STS_AGD_MEDIAP = 0
		AND AGD.DT_AGD_MEDIAP <= CONVERT(VARCHAR(10),GETDATE(), 101)		
		
END	
