IF EXISTS (SELECT * FROM sys.objects
		  WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_PROD_CPL_VD_PROC_EXEC_ALL]')
			 AND type IN ( N'P', N'PC') )
    DROP PROCEDURE [dbo].[P_EST_PROD_CPL_VD_PROC_EXEC_ALL];
GO

GO
--EXEC P_EST_PROD_CPL_VD_PROC_EXEC_ALL 201709
CREATE PROCEDURE P_EST_PROD_CPL_VD_PROC_EXEC_ALL @ANO_MES_REPROC INT
AS
    SET NOCOUNT ON;
    SET ANSI_WARNINGS OFF;
    DECLARE @CD_FILIAL INT;
	DECLARE @CD_EMP INT;
    BEGIN TRY
	   DECLARE FILIAIS CURSOR FAST_FORWARD FOR
		  SELECT
			 CD_EMP,
			 CD_FILIAL
		  FROM
			 PRC_FILIAL
		  WHERE
			 STS_FILIAL = 0;

	   OPEN FILIAIS;
	   FETCH NEXT FROM FILIAIS INTO @CD_EMP, @CD_FILIAL;

	   WHILE @@FETCH_STATUS = 0
		  BEGIN
			 PRINT '  Filial ' + CONVERT(VARCHAR(5), @CD_FILIAL) + ' (' + CONVERT(VARCHAR(8), GETDATE(), 114) + ')...';

			 EXEC P_EST_PROD_CPL_VD_PROC @CD_EMP, @CD_FILIAL,0,@ANO_MES_REPROC

			 FETCH NEXT FROM FILIAIS INTO @CD_EMP, @CD_FILIAL ;
		  END ;

	   PRINT 'Concluido.' ;
	   CLOSE FILIAIS ;
	   DEALLOCATE FILIAIS ;
	   
	   PRINT 'Consolidar vendas rede '+CONVERT(VARCHAR, GETDATE(), 108);
	   EXEC P_EST_PROD_VD_PROC 1, @ANO_MES_REPROC;

	END TRY
    BEGIN CATCH

		CLOSE FILIAIS ;
		DEALLOCATE FILIAIS ;
		DECLARE @ErrorMessage VARCHAR(4000) = ERROR_MESSAGE();
		DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
		DECLARE @ErrorState INT = ERROR_STATE();

		INSERT INTO ADM_ERRO ( numero ,severidade ,estado ,rotina ,linha ,mensagem ,dtErro )
			SELECT
				ERROR_NUMBER()	  AS numero
				,@ErrorSeverity	  AS severidade
				,@ErrorState		  AS estado
				,'P_EST_PROD_CPL_VD_PROC_EXEC_ALL'	  AS rotina
				,ERROR_LINE()		  AS linha
				,@ErrorMessage	  AS mensagem
				,GETDATE()		  AS dtErro ;

	    RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);

    END CATCH;
    
    

