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

--EXEC P_EXP_CTB_EXP_MOV_PROC_ALL 1,'', '2017-04-01','2017-04-30'

CREATE PROCEDURE P_EXP_CTB_EXP_MOV_PROC_ALL @CD_EMP_PAR INT, 
										    @FILIAIS VARCHAR(MAX)='', 
											@DT_INI DATETIME, 
											@DT_FIM DATETIME 
AS
	 
	SET NOCOUNT ON;
	DECLARE @CD_EMP INT;
	DECLARE @CD_FILIAL INT;

	--BEGIN TRY
			create table #tmp_filial(CD_EMP int, CD_FILIAL int)
			IF LTRIM(RTRIM(@FILIAIS))<>''
			begin
				insert into #tmp_filial
				SELECT @CD_EMP_PAR, ID FROM UFD_PRM_IN_STRING(@FILIAIS)
			end
			
			IF LTRIM(RTRIM(@FILIAIS))=''
			begin
				insert into #tmp_filial
				SELECT CD_EMP, CD_FILIAL FROM PRC_FILIAL WHERE CD_EMP = @CD_EMP_PAR
			end
			
			PRINT 'SELECT 1 '+CONVERT(VARCHAR, GETDATE(), 108);
			DECLARE ProcMovfiliaisCTB CURSOR FAST_FORWARD
			FOR SELECT DISTINCT
					CD_EMP,
					CD_FILIAL
			FROM 
				#tmp_filial 
			 
			OPEN ProcMovfiliaisCTB;
			FETCH NEXT FROM ProcMovfiliaisCTB INTO
												 @CD_EMP
											   , @CD_FILIAL;
			WHILE @@FETCH_STATUS = 0
				BEGIN

					PRINT 'EXEC 2 '+CONVERT(VARCHAR, GETDATE(), 108);
					PRINT '=============================  FILIAL.: '+CONVERT(VARCHAR, @CD_FILIAL, 10) + '       =============================';
					EXEC P_EXP_CTB_EXP_MOV @CD_EMP,@CD_FILIAL,@DT_INI,@DT_FIM,0

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

			CLOSE ProcMovfiliaisCTB;
			DEALLOCATE ProcMovfiliaisCTB;
/*		
	END TRY
	
BEGIN CATCH 
	
	INSERT INTO ADM_ERRO (numero, severidade, estado, rotina, linha, mensagem, dtErro)
		SELECT
			ERROR_NUMBER() AS numero,
			ERROR_SEVERITY() AS severidade,
			ERROR_STATE() AS estado,
			'P_EXP_CTB_EXP_MOV_PROC_ALL' AS rotina,
			ERROR_LINE() AS linha,
			ERROR_MESSAGE() AS mensagem,
			GETDATE() AS dtErro;	
	
END CATCH
*/

PRINT 'P_EXP_CTB_EXP_MOV_PROC_ALL FINALIZADA!';