IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_PROD_PENDENCIA_ENTRADA_RESSUPRIMENTO]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[P_EST_PROD_PENDENCIA_ENTRADA_RESSUPRIMENTO]
GO

CREATE PROCEDURE P_EST_PROD_PENDENCIA_ENTRADA_RESSUPRIMENTO
AS

BEGIN

DECLARE @CD_FILIAL INT
DECLARE @CD_EMP INT

DECLARE cFilialPendencia CURSOR FAST_FORWARD READ_ONLY FOR 
	SELECT  
	 	CD_FILIAL
	FROM 
		PRC_FILIAL
	WHERE
		STS_FILIAL=0
		AND CD_EMP=1
	ORDER BY CD_FILIAL
	
	OPEN cFilialPendencia
	FETCH NEXT FROM cFilialPendencia INTO @CD_FILIAL

	WHILE @@FETCH_STATUS=0
	BEGIN
	 
		Print 'Atualizando Filial ..: ' + convert(varchar, @CD_FILIAL) + ' '	
		--Remove danfes pendencia		
		DELETE FROM P
		FROM 
			EST_NF_ENT_DANFE_PROVISORIO_PENDENTE P
			JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT E ON 
				P.CD_CTR=E.CD_CTR
		WHERE 
			E.CD_EMP=@CD_EMP
			AND E.CD_FILIAL=@CD_FILIAL;

		EXECUTE dbo.P_EST_PROD_PENDENCIA_ENTRADA_FILIAL @CD_EMP, @CD_FILIAL;
	
		FETCH NEXT FROM  cFilialPendencia INTO @CD_FILIAL 
	END

    CLOSE cFilialPendencia
    DEALLOCATE cFilialPendencia
END