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

CREATE PROCEDURE [dbo].[P_PROCESSA_PENDENCIA_IBS_CBS_EXECUTE_ALL]
AS
BEGIN

	 EXEC sys.sp_set_session_context 
         @key = N'ALLOW_PENDENCIA_IBS_CBS',
         @value = 1;

    DECLARE @CD_TRIB_IBS_CBS INT;
	DECLARE @CD_FILIAL INT;

	DECLARE cur_pendencias CURSOR LOCAL FAST_FORWARD FOR
		SELECT DISTINCT CD_TRIB_IBS_CBS, CD_FILIAL
		FROM EST_PROD_CPL_IBS_CBS_PEND
		WHERE STS_GERACAO = 0;
	OPEN cur_pendencias;
	FETCH NEXT FROM cur_pendencias INTO @CD_TRIB_IBS_CBS, @CD_FILIAL;
	WHILE @@FETCH_STATUS = 0
	BEGIN
		BEGIN TRY
			EXEC dbo.P_PROCESSA_PENDENCIA_IBS_CBS @CD_TRIB_IBS_CBS, @CD_FILIAL;
		END TRY
		BEGIN CATCH
			PRINT 'Erro ao processar CD_TRIB_IBS_CBS = ' + CAST(@CD_TRIB_IBS_CBS AS VARCHAR(20));
			THROW;
		END CATCH;
		FETCH NEXT FROM cur_pendencias INTO @CD_TRIB_IBS_CBS, @CD_FILIAL;
	END
	CLOSE cur_pendencias;
	DEALLOCATE cur_pendencias;

	  EXEC sys.sp_set_session_context 
         @key = N'ALLOW_PENDENCIA_IBS_CBS',
         @value = NULL;
END;