GO
IF EXISTS(SELECT * FROM SYS.OBJECTS
			WHERE  OBJECT_ID = OBJECT_ID(N'[DBO].[P_PDV_VD_CORRECAO_VALORES_EXEC_ALL]') AND TYPE IN(N'P', N'PC'))
DROP PROCEDURE [DBO].[P_PDV_VD_CORRECAO_VALORES_EXEC_ALL];
GO

GO

--P_PDV_VD_CORRECAO_VALORES_EXEC_ALL 1,2018,09,0
CREATE PROCEDURE [dbo].[P_PDV_VD_CORRECAO_VALORES_EXEC_ALL](@CD_EMP   INT = 1
																, @ANO  INT
																, @MES  INT
																, @CdFilialPar int=0)
AS
BEGIN
	SET NOCOUNT ON;
	SET ANSI_WARNINGS OFF;
	DECLARE @cdFilial int ;

	DECLARE @DT_REF DATETIME
	DECLARE @DT_INI DATETIME;
	DECLARE @DT_FIM DATETIME
	
	IF @ANO >0 AND @MES>0
	BEGIN
		SET @DT_INI=CONVERT(VARCHAR,@ANO*100+@MES) +'01';
		SET @DT_FIM=dbo.F_FINAL_MES(@DT_INI)
	END
	SET @DT_REF =@DT_INI; 	
	DECLARE c_FilialCorrecao CURSOR FAST_FORWARD READ_ONLY FOR
	SELECT CD_FILIAL  
		FROM PRC_FILIAL 
		WHERE CD_FILIAL = CASE WHEN @CdFilialPar>0 THEN @CdFilialPar ELSE CD_FILIAL END
		ORDER BY CD_FILIAL

	OPEN c_FilialCorrecao
	FETCH NEXT FROM c_FilialCorrecao INTO @cdFilial
	WHILE @@FETCH_STATUS = 0
		BEGIN
			PRINT 'Procesando lj ' + CONVERT(VARCHAR, @cdFilial) 
			WHILE @DT_REF <= @DT_FIM
			BEGIN	 
				PRINT 'Procesando  data ' + CONVERT(char(10), @DT_REF,112) + ' proc ' + CONVERT(char(8), getdate(),114)
				EXEC P_PDV_VD_CORRECAO_VALORES @CD_EMP, @cdFilial, @DT_REF
				EXEC P_EST_PROD_VD_PROC_REPROCESSAMENTO_ALL 0,@cdFilial,@DT_REF
				SET @DT_REF=DATEADD(DAY,1,@DT_REF);
			END
			SET @DT_REF =@DT_INI; 	
			FETCH NEXT FROM c_FilialCorrecao INTO @cdFilial
		END
	CLOSE c_FilialCorrecao;
	DEALLOCATE c_FilialCorrecao; 
END