/****** Object:  StoredProcedure [dbo].[P_EST_PROD_CPL_ULT_MOV_PDV_VD_PROC_ALL]    Script Date: 11/07/2013 18:13:23 ******/
IF EXISTS( SELECT * FROM sys.objects
				WHERE  object_id = OBJECT_ID(N'[dbo].[P_EST_PROD_CPL_ULT_MOV_PDV_VD_PROC_ALL]')
					   AND type IN(N'P', N'PC')
)
	BEGIN
		DROP PROCEDURE [dbo].[P_EST_PROD_CPL_ULT_MOV_PDV_VD_PROC_ALL];
	END;
GO
GO
GO
--EXEC P_EST_PROD_CPL_ULT_MOV_PDV_VD_PROC_ALL 180

CREATE PROCEDURE [dbo].[P_EST_PROD_CPL_ULT_MOV_PDV_VD_PROC_ALL] @QTDE_PROC INT=180, 
																@CD_FILIAL_PAR INT=0,
																@DT_PROC DATETIME=NULL,
																@FLAG_REPROCESSAR INT=0
AS
	IF @CD_FILIAL_PAR =0 AND @FLAG_REPROCESSAR=1
	BEGIN
		TRUNCATE TABLE EST_PROD_CPL_ULT_MOV_PDV_VD;
	END 
	 BEGIN
		 PRINT 'Inicio da analise de vendas de produtos ultima venda';
		 SET NOCOUNT ON;
		 DECLARE @CD_FILIAL INT;
		 DECLARE @CD_EMP INT;

		PRINT 'Periodo '+ CONVERT(CHAR(10), @QTDE_PROC)+CONVERT(VARCHAR(10), GETDATE(), 108);

		 DECLARE ProcProcVendas CURSOR FAST_FORWARD
		 FOR SELECT
				CD_EMP
				,CD_FILIAL
			 FROM
				 PRC_FILIAL
			 WHERE  CD_FILIAL = CASE
									WHEN @CD_FILIAL_PAR > 0 THEN @CD_FILIAL_PAR
									ELSE CD_FILIAL
								END;



		 OPEN ProcProcVendas;
		 FETCH NEXT FROM ProcProcVendas INTO @CD_EMP
											  , @CD_FILIAL;
		 WHILE @@FETCH_STATUS = 0
			 BEGIN
				 PRINT 'Filial '+CONVERT(VARCHAR(10), @CD_FILIAL)+' '+CONVERT(VARCHAR, GETDATE(), 108);


				EXEC P_EST_PROD_CPL_ULT_MOV_PDV_VD_PROC @QTDE_PROC,@CD_EMP,@CD_FILIAL,@DT_PROC

				 FETCH NEXT FROM ProcProcVendas INTO @CD_EMP
													  , @CD_FILIAL;
			 END;
		 PRINT 'Concluido.';
		 CLOSE ProcProcVendas;
		 DEALLOCATE ProcProcVendas;
	 END;