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

GO

--P_INCLUI_PONTOS_FIDEL_EXEC_ALL 1,2018,07,0
CREATE PROCEDURE [dbo].[P_INCLUI_PONTOS_FIDEL_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_FilialCorrecaoPontuacao 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_FilialCorrecaoPontuacao
	FETCH NEXT FROM c_FilialCorrecaoPontuacao 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)
				EXECUTE P_INCLUI_PONTOS_FIDEL 0,0,0,0, @DT_REF, @DT_REF
				SET @DT_REF=DATEADD(DAY,1,@DT_REF);
			END
			SET @DT_REF =@DT_INI; 	
			FETCH NEXT FROM c_FilialCorrecaoPontuacao INTO @cdFilial
		END
	CLOSE c_FilialCorrecaoPontuacao;
	DEALLOCATE c_FilialCorrecaoPontuacao; 
	--Refaz saldo do cliente
	EXECUTE P_ATUALIZA_SALDO_FIDELIDADE;
END