/****** Object:  StoredProcedure [dbo].[P_EST_PROD_INVENTARIO_EXECUTE_ALL]    Script Date: 15/10/2014 11:32:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_PROD_INVENTARIO_EXECUTE_ALL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_EST_PROD_INVENTARIO_EXECUTE_ALL]
GO
--EXEC P_EST_PROD_INVENTARIO_EXECUTE_ALL 1,2016,12,1
CREATE PROCEDURE [dbo].[P_EST_PROD_INVENTARIO_EXECUTE_ALL] @CD_EMP INT=1, @ANO INT=NULL, @MES VARCHAR(2)=NULL, @TIPO_CUSTO INT=0 AS 
	SET NOCOUNT ON
	
	DECLARE @CD_FILIAL INT, @MESFECHAMENTO DATETIME
	 	
	IF @ANO IS NULL OR @MES IS NULL
		SELECT 
			@MESFECHAMENTO=DATEADD(MONTH, -1, GETDATE()), 
			@ANO=YEAR(@MESFECHAMENTO), 
			@MES=MONTH(@MESFECHAMENTO)
			

	IF  LEN(@MES)=1 
		SET @MES='0' + @MES

	SELECT @MESFECHAMENTO = CONVERT(CHAR(4), @ANO) + CONVERT(CHAR(2), @MES) + '01'
	PRINT 'Registro de inventario - ' + RIGHT(CONVERT(CHAR(10),@MESFECHAMENTO,103),7)+ ':'
	
	DECLARE FILIAIS CURSOR FAST_FORWARD FOR 
	SELECT CD_FILIAL 
	FROM 
		PRC_FILIAL 
	WHERE 
		NOT CD_FILIAL BETWEEN 300 AND 400  
		AND CD_EMP=1
	ORDER BY CD_FILIAL
	
	OPEN FILIAIS
	
	FETCH NEXT FROM FILIAIS INTO @CD_FILIAL
	WHILE @@FETCH_STATUS=0
	  BEGIN
		PRINT	'  FILIAL ' + CONVERT(VARCHAR(5), @CD_FILIAL) + 
				' (' + CONVERT(VARCHAR(8), GETDATE(), 114) + ')...'
				
		EXECUTE P_EST_PROD_INVENTARIO @CD_EMP,@ANO, @MES, @CD_FILIAL,  1,1,0,0,'',@TIPO_CUSTO
		
		FETCH NEXT FROM FILIAIS INTO @CD_FILIAL
	  END
	  
	PRINT 'CONCLUiDO.'
	CLOSE FILIAIS
	DEALLOCATE FILIAIS
