IF OBJECT_ID('P_GERA_PDV_MAPA_RESUMO') IS NOT NULL
    BEGIN
	   DROP PROCEDURE P_GERA_PDV_MAPA_RESUMO;
    END;
GO 
--EXEC P_GERA_PDV_MAPA_RESUMO 1,'1,2,3','2018-05-01','2018-05-31',1
CREATE PROCEDURE P_GERA_PDV_MAPA_RESUMO (@CD_EMP INT =1, @FILIAIS VARCHAR(8000), @DATAINI DATE,  @DATAFIM DATE, @REFAZER TINYINT )
AS 
set nocount on;

/*****************************************************************************************************************************************/

--Testes

/*
deClare @cd_emp int =1, 
		@Filiais varchar(8000) = '1,10', 
		@DataIni date  ='20180103',  
		@DataFim date ='20180105',
		@Refazer TinyInt = 0

	/* 
		drop table #TblFilial
		drop table #TblMov 
		drop table #TblMapa
	*/
 
*/
 
/*****************************************************************************************************************************************/
Declare @sCmd Varchar(5000)

    Print 'Inicio da rotina P_GERA_PDV_MAPA_RESUMO - Time : ' + convert(varchar,getdate(),108);
	
	create table #TblFilial (CD_FILIAL INT) 
	set @sCmd ='insert into #TblFilial 
				SELECT 
					CD_filial
				FROM 
					PRC_FILIAL 
				WHERE
					CD_EMP= ' + convert(varchar, @CD_EMP) + '
					AND STS_FILIAL =0
					AND CD_FILIAL IN ( ' + @Filiais + ')'

	exec (@sCmd);

	CREATE TABLE #RSCALENDARIO(CD_EMP INT,DT DATETIME);
	DECLARE @START DATETIME, @END DATETIME;
	SET @START = @DATAINI;
	SET @END = @DATAFIM;
	
	PRINT 'Criando periodo para geracao '+CONVERT(VARCHAR, GETDATE(), 108);
	WITH CALENDAR(DATE)
     AS (
     SELECT @START
     UNION ALL
     SELECT DATE + 1
     FROM CALENDAR
     WHERE DATE  < @END)
     INSERT INTO #RSCALENDARIO(DT)
            SELECT *
            FROM calendar OPTION(MAXRECURSION 10000); 

/*****************************************************************************************************************************************/
	Print 'Carregando movimentos da analise.. - Time : ' + convert(varchar,getdate(),108);
	DECLARE @CodFilial int,
			@Data Date  
							
	declare cFilialProcMapa CURSOR FAST_FORWARD FOR
	select distinct 
		cd_filial,
		c.DT
	from 
		#TblFiliaL,#RSCALENDARIO C
	ORDER BY
		cd_filial,
		c.DT
		
	OPEN cFilialProcMapa
	FETCH NEXT FROM cFilialProcMapa INTO @CodFilial , @Data
	WHILE @@FETCH_STATUS = 0
		BEGIN
			PRINT 'Procesando filial ' + CONVERT(VARCHAR, @CodFilial ) + ' dia ' + convert(Varchar, @Data ) + ' - Time ' + convert(varchar,getdate(),108)

			EXECUTE P_GERA_PDV_MAPA_RESUMO_GERACAO @Cd_emp,@CodFilial,@Data,@REFAZER;
			FETCH NEXT FROM cFilialProcMapa INTO @CodFilial ,@Data
		END

	CLOSE cFilialProcMapa;
	DEALLOCATE cFilialProcMapa; 
		
/*****************************************************************************************************************************************/		