/****** Object:  StoredProcedure [dbo].[P_EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_COMPARACAO_ALL]    Script Date: 11/28/2013 09:36:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_COMPARACAO_ALL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_COMPARACAO_ALL]
GO
GO

--Versao 3252
--EXECUTE P_EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_COMPARACAO_ALL 07, 2018,0
CREATE PROCEDURE [dbo].[P_EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_COMPARACAO_ALL](@MES INT=NULL, 
																				 @ANO INT=NULL,
																				 @CD_FILIAL_PAR INT=0 )  AS
	DECLARE @CD_FILIAL INT
	DECLARE @DT_ENT DATETIME
	DECLARE @CD_CTR INT
	DECLARE @AGORA DATETIME
	
	SET NOCOUNT ON
	IF @ANO IS NULL OR @MES IS NULL
		begin
			SELECT @AGORA=DATEADD(month, -1, GETDATE()), @ANO=YEAR(@AGORA), @MES=MONTH(@AGORA)
		end
	 
	DECLARE CFilialProcDanfe CURSOR FAST_FORWARD READ_ONLY FOR 
	SELECT  
		EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_CTR,
		EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_FILIAL,
		EST_NF_ENT.DT_ENT
	FROM 
		EST_NF_ENT INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT ON
		EST_NF_ENT.CD_EMP = EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_EMP AND
		EST_NF_ENT.CD_FILIAL = EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_FILIAL AND
		EST_NF_ENT.CD_NF = EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_NF 
	WHERE 
		EST_NF_ENT.CD_EMP = 1  
		AND EST_NF_ENT.CD_FILIAL = CASE WHEN @CD_FILIAL_PAR = 0 THEN EST_NF_ENT.CD_FILIAL ELSE @CD_FILIAL_PAR END
		AND YEAR(EST_NF_ENT.DT_ENT)=@ANO
		AND MONTH(EST_NF_ENT.DT_ENT)=@MES 
	ORDER BY
		EST_NF_ENT.CD_FILIAL,
		EST_NF_ENT.DT_ENT
	
	OPEN CFilialProcDanfe
	FETCH NEXT FROM CFilialProcDanfe INTO @CD_CTR,@CD_FILIAL,@DT_ENT

	WHILE @@FETCH_STATUS=0
	BEGIN
		PRINT 'Codigo DANFE ' + CONVERT(VARCHAR, @CD_CTR)  + ' filial ' + CONVERT(VARCHAR, @CD_FILIAL) + ' data ' +  CONVERT(CHAR(10), @DT_ENT,112)
		EXECUTE P_EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_COMPARACAO @CD_CTR;
		FETCH NEXT FROM  CFilialProcDanfe INTO @CD_CTR,@CD_FILIAL,@DT_ENT
	END
CLOSE CFilialProcDanfe
DEALLOCATE CFilialProcDanfe