SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- [PRDEX_GET_INPUT]
-- =================================================================
-- Collect head informations of export data and 
-- 
-- Returns: INTEGER; 0 = ok; 0 <> nicht ok
-- =================================================================
-- Copyright (c) 2025 by Digital Data GmbH
--
-- Digital Data GmbH • Ludwig-Rinn-Strasse 16 • D-35452 Heuchelheim
-- Tel.: 0641/202360 • E-Mail: info-flow@digitaldata.works
-- =================================================================
-- Creation Date / Author:    01.08.2025 / MK
-- Version Date / Editor:     01.08.2025 / MK
-- Version Number:            1.0.0.0
-- =================================================================
-- History:
-- 01.08.2025 / MK - First Version

CREATE OR ALTER PROCEDURE [dbo].[PRDEX_GET_INPUT](
	@pPROFILE_ID			BIGINT,
	@pTEST_MODE				BIT,
	@pASYNC_MODE			BIT,
	@pBATCH_ID				NVARCHAR(25),
	@pBATCH_CREATOR			NVARCHAR(50),
	@pLANGUAGE				NVARCHAR(10),
	@pLOG_LEVEL				NVARCHAR(25),
	@pSTART_QUERY			NVARCHAR(MAX),
	@pSTART_QUERY_VAR1		NVARCHAR(50),
	@pSTART_QUERY_VAR2		NVARCHAR(50),
	@pSTART_QUERY_VAR3		NVARCHAR(50),
	@pSTART_QUERY_VAR4		NVARCHAR(50),
	@pSTART_QUERY_VAR5		NVARCHAR(50),
	@pFORCE					BIT,
	@pPROFILE_NAME			NVARCHAR(50),
	@pMANDANTOR				NVARCHAR(50),
	@pEXPORT_TYPE			NVARCHAR(50)
)
AS
BEGIN TRY

	SET NOCOUNT ON;
	SET XACT_ABORT ON;

	-- declare new vars because of parameter sniffing
	DECLARE @PROFILE_ID						BIGINT			= @pPROFILE_ID,
			@TEST_MODE						BIT				= @pTEST_MODE,
			@ASYNC_MODE						BIT				= @pASYNC_MODE,
			@BATCH_ID						NVARCHAR(25)	= @pBATCH_ID,
			@BATCH_CREATOR					NVARCHAR(25)	= @pBATCH_CREATOR,
			@LANGUAGE						NVARCHAR(10)	= @pLANGUAGE,
			@LOG_LEVEL						NVARCHAR(25)	= UPPER(ISNULL(@pLOG_LEVEL,'INFO')),
			@START_QUERY					NVARCHAR(MAX)	= @pSTART_QUERY,
			@START_QUERY_VAR1				NVARCHAR(50)	= @pSTART_QUERY_VAR1,
			@START_QUERY_VAR2				NVARCHAR(50)	= @pSTART_QUERY_VAR2,
			@START_QUERY_VAR3				NVARCHAR(50)	= @pSTART_QUERY_VAR3,
			@START_QUERY_VAR4				NVARCHAR(50)	= @pSTART_QUERY_VAR4,
			@START_QUERY_VAR5				NVARCHAR(50)	= @pSTART_QUERY_VAR5,
			@FORCE							BIT				= @pFORCE,
			@PROFILE_NAME					NVARCHAR(50)	= @pPROFILE_NAME,
			@MANDANTOR						NVARCHAR(50)	= @pMANDANTOR,
			@EXPORT_TYPE					NVARCHAR(50)	= @pEXPORT_TYPE;

	-- declare virtual table for found data
	DECLARE	@vTBDEX_IN as TABLE (
			[GUID]							[bigint] IDENTITY(1,1)	NOT NULL,
			[PROFILE_ID]					[smallint]				NOT NULL,
			[BATCH_ID]						[nvarchar](25)			NOT NULL,
			[REFERENCE1]					[nvarchar](150)			NOT NULL,
			[REFERENCE2]					[nvarchar](150)			NULL,
			[REFERENCE3]					[nvarchar](150)			NULL,
			[REFERENCE4]					[nvarchar](150)			NULL,
			[REFERENCE5]					[nvarchar](150)			NULL,
			[EXTERNAL_REFERENCE1]			[nvarchar](2000)		NULL,
			[EXTERNAL_REFERENCE2]			[nvarchar](2000)		NULL,
			[EXTERNAL_REFERENCE3]			[nvarchar](2000)		NULL,
			[EXTERNAL_REFERENCE4]			[nvarchar](2000)		NULL,
			[EXTERNAL_REFERENCE5]			[nvarchar](2000)		NULL,
			[TEST_MODE]						[bit]      				NOT NULL,
			[ASYNC_MODE]					[bit]      				NOT NULL,
			[COMMENT]						[nvarchar](150)			NULL,
			[ADDED_WHO]						[nvarchar](50)			NOT NULL,
			[ADDED_WHEN]					[datetime]				NOT NULL);

	-- declare runtime vars
    DECLARE @MY_PROCEDURE_NAME				 NVARCHAR(128)	= OBJECT_NAME(@@PROCID);
	DECLARE	@ACTIVE_FLAG					 BIT			= 1,
			@INACTIVE_FLAG					 BIT			= 0,
			@ROW_COUNT1						 SMALLINT		= 0,
			@ROW_COUNTER_INPUT				 SMALLINT		= 0,
			@QUERY_KEYWORD					 NVARCHAR(50)	= 'QUERY',
			@DB_VERSION						 NVARCHAR(25)	= NULL,
			@QUERY_GET_INPUT				 NVARCHAR(MAX)	= NULL,
			@REFERENCE1						 NVARCHAR(150)	= 0,
			@REFERENCE2						 NVARCHAR(150)	= NULL,
			@REFERENCE3						 NVARCHAR(150)	= NULL,
			@REFERENCE4						 NVARCHAR(150)	= NULL,
			@REFERENCE5						 NVARCHAR(150)	= NULL,
			@EXTERNAL_REFERENCE1			 NVARCHAR(250)	= NULL,
			@EXTERNAL_REFERENCE2			 NVARCHAR(250)	= NULL,
			@EXTERNAL_REFERENCE3			 NVARCHAR(250)	= NULL,
			@EXTERNAL_REFERENCE4			 NVARCHAR(250)	= NULL,
			@EXTERNAL_REFERENCE5			 NVARCHAR(250)	= NULL,
			@PLACEHOLDER_NAME				 NVARCHAR(50)	= NULL,
			@PLACEHOLDER					 NVARCHAR(MAX)	= NULL,
			@PLACEHOLDER_TYPE				 NVARCHAR(10)	= 'CONST',
			@TBDEX_TMP_TABLE_SCHEMA			 SYSNAME		= SCHEMA_NAME(),
			@TBDEX_TMP_TABLE_NAME			 SYSNAME		= CONCAT(N'##TBDEX_TMP_CONTENT_BATCH_',@BATCH_ID),
			@TBDEX_TMP_TABLE_SCHEMA_AND_NAME NVARCHAR(150)	= NULL,
			@TBDEX_TMP_TABLE_COLUMNS		 NVARCHAR(MAX)	= NULL,
			@TBDEX_TMP_TABLE_DROP_QUERY		 NVARCHAR(MAX)	= NULL,
			@TBDEX_TMP_TABLE_CREATE_QUERY	 NVARCHAR(MAX)	= NULL,
			@TBDEX_TMP_TABLE_INSERT_QUERY	 NVARCHAR(MAX)	= NULL,
			@TBDEX_TMP_TABLE_CONTENT		 NVARCHAR(MAX)	= NULL,
			@RETURN_STATUS					 INT			= 0,
			@RETURN_STATUS_TEXT				 NVARCHAR(MAX)	= concat('START PROCEDURE [',@MY_PROCEDURE_NAME,'] @ ',CONVERT(varchar(50),GETDATE(),120)),
			@RETURN_ERROR_TEXT				 NVARCHAR(MAX)	= '';

	PRINT '====================================================================================================';
	PRINT @RETURN_STATUS_TEXT;
	PRINT '';
	PRINT 'PARAMETER01 - @PROFILE_ID:       ' + CONVERT(NVARCHAR(50),ISNULL(@PROFILE_ID,'<NO-VALUE>'));
	PRINT 'PARAMETER02 - @TEST_MODE:        ' + CONVERT(NVARCHAR(50),ISNULL(@TEST_MODE,'<NO-VALUE>'));
	PRINT 'PARAMETER03 - @ASYNC_MODE:       ' + CONVERT(NVARCHAR(50),ISNULL(@ASYNC_MODE,'<NO-VALUE>'));
	PRINT 'PARAMETER04 - @BATCH_ID:         ' + CONVERT(NVARCHAR(50),ISNULL(@BATCH_ID,'<NO-VALUE>'));
	PRINT 'PARAMETER05 - @BATCH_CREATOR:    ' + CONVERT(NVARCHAR(50),ISNULL(@BATCH_CREATOR,'<NO-VALUE>'));
	PRINT 'PARAMETER06 - @LANGUAGE:         ' + CONVERT(NVARCHAR(50),ISNULL(@LANGUAGE,'<NO-VALUE>'));
	PRINT 'PARAMETER07 - @LOG_LEVEL:        ' + CONVERT(NVARCHAR(50),ISNULL(@LOG_LEVEL,'<NO-VALUE>'));
	PRINT 'PARAMETER08 - @START_QUERY:      ' + CONVERT(NVARCHAR(50),ISNULL(@START_QUERY,'<NO-VALUE>'));
	PRINT 'PARAMETER09 - @START_QUERY_VAR1: ' + CONVERT(NVARCHAR(50),ISNULL(@START_QUERY_VAR1,'<NO-VALUE>'));
	PRINT 'PARAMETER10 - @START_QUERY_VAR2: ' + CONVERT(NVARCHAR(50),ISNULL(@START_QUERY_VAR2,'<NO-VALUE>'));
	PRINT 'PARAMETER11 - @START_QUERY_VAR3: ' + CONVERT(NVARCHAR(50),ISNULL(@START_QUERY_VAR3,'<NO-VALUE>'));
	PRINT 'PARAMETER12 - @START_QUERY_VAR4: ' + CONVERT(NVARCHAR(50),ISNULL(@START_QUERY_VAR4,'<NO-VALUE>'));
	PRINT 'PARAMETER13 - @START_QUERY_VAR5: ' + CONVERT(NVARCHAR(50),ISNULL(@START_QUERY_VAR5,'<NO-VALUE>'));
	PRINT 'PARAMETER14 - @FORCE:            ' + CONVERT(NVARCHAR(50),ISNULL(@FORCE,'<NO-VALUE>'));
	PRINT 'PARAMETER15 - @PROFILE_NAME:     ' + CONVERT(NVARCHAR(50),ISNULL(@PROFILE_NAME,'<NO-VALUE>'));
	PRINT 'PARAMETER16 - @MANDANTOR:        ' + CONVERT(NVARCHAR(50),ISNULL(@MANDANTOR,'<NO-VALUE>'));
	PRINT 'PARAMETER17 - @EXPORT_TYPE:      ' + CONVERT(NVARCHAR(50),ISNULL(@EXPORT_TYPE,'<NO-VALUE>'));
	PRINT '';

	--===================================================-- Log result to table --===================================================--
	IF (@LOG_LEVEL in ('INFO')) BEGIN
		EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
								@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
								@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
								@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	--==================================================-- Get first sql query --===================================================--
	IF (((UPPER(@START_QUERY) LIKE 'SELECT%') OR (UPPER(@START_QUERY) LIKE '%SELECT%')) AND (UPPER(@START_QUERY) LIKE '%FROM%')) BEGIN

		SET @QUERY_GET_INPUT = LTRIM(RTRIM(@START_QUERY));

	END; ELSE IF ((SELECT count(*) 
				   FROM  [TBDEX_CFG_RESOURCES] 
				   WHERE [PROFILE_ID] IN (0,@PROFILE_ID) AND [ACTIVE] = @ACTIVE_FLAG 
				   AND   LTRIM(RTRIM([PLACEHOLDER_NAME])) = @START_QUERY AND LTRIM(RTRIM([PLACEHOLDER_TYPE])) = @QUERY_KEYWORD) >= 1) BEGIN

		SET @QUERY_GET_INPUT = (SELECT TOP 1 LTRIM(RTRIM([PLACEHOLDER]))
								FROM  [TBDEX_CFG_RESOURCES] 
								WHERE [PROFILE_ID] IN (@PROFILE_ID,0) AND [ACTIVE] = @ACTIVE_FLAG 
								AND   LTRIM(RTRIM([PLACEHOLDER_NAME])) = @START_QUERY AND LTRIM(RTRIM([PLACEHOLDER_TYPE])) = @QUERY_KEYWORD
								ORDER BY [PROFILE_ID] ASC,[GUID] DESC);

	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	--=================================================-- Check first sql query --===================================================--
	IF (LEN(@QUERY_GET_INPUT) < 15) BEGIN

		--====================================================-- exception / error --====================================================--
		SET @RETURN_STATUS		= 50001;
		SET @RETURN_STATUS_TEXT = concat('Wrong call or configuraton!','');
		SET @RETURN_ERROR_TEXT	= concat('Found no valid querys (query needs to be 15 chars or more)!','');

        THROW @RETURN_STATUS,@RETURN_ERROR_TEXT,1;
		-----------------------------------------------------------------------------------------------------------------------------------

	END; ELSE BEGIN

		--======================================================-- Output result --======================================================--
		SET @RETURN_STATUS		= 0;
		SET @RETURN_STATUS_TEXT = concat('Found "@QUERY_GET_INPUT" query: ',char(13),@QUERY_GET_INPUT);
		SET @RETURN_ERROR_TEXT	= concat('','');
		
		PRINT '';
		PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
		-----------------------------------------------------------------------------------------------------------------------------------

		--===================================================-- Log result to table --===================================================--
		IF (@LOG_LEVEL in ('INFO')) BEGIN
			EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
									@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
									@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
									@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
		END;
		-----------------------------------------------------------------------------------------------------------------------------------

	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	--==================================================-- Handle placeholders  --==================================================--
	PRINT '';
	PRINT 'Replacing placeholders in query...';
		
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%PROFILE_ID%',ISNULL(@PROFILE_ID,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%TEST_MODE%',ISNULL(@TEST_MODE,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%ASYNC_MODE%',ISNULL(@ASYNC_MODE,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%BATCH_ID%',ISNULL(@BATCH_ID,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%BATCH_CREATOR%',ISNULL(@BATCH_CREATOR,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%LANGUAGE%',ISNULL(@LANGUAGE,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%LOG_LEVEL%',ISNULL(@LOG_LEVEL,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%START_QUERY%',ISNULL(@START_QUERY,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%START_QUERY_VAR1%',ISNULL(@START_QUERY_VAR1,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%START_QUERY_VAR2%',ISNULL(@START_QUERY_VAR2,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%START_QUERY_VAR3%',ISNULL(@START_QUERY_VAR3,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%START_QUERY_VAR4%',ISNULL(@START_QUERY_VAR4,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%START_QUERY_VAR5%',ISNULL(@START_QUERY_VAR5,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%FORCE%',ISNULL(@FORCE,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%MY_PROCEDURE_NAME%',ISNULL(@MY_PROCEDURE_NAME,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%PROFILE_NAME%',ISNULL(@PROFILE_NAME,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%MANDANTOR%',ISNULL(@MANDANTOR,''));
	SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,'%EXPORT_TYPE%',ISNULL(@EXPORT_TYPE,''));

	DECLARE CURSOR_PLACEHOLDER CURSOR
	LOCAL FAST_FORWARD FOR 
		SELECT [PLACEHOLDER_NAME] as 'Placeholder_Name', [PLACEHOLDER] as 'Placeholder'
		FROM   [TBDEX_CFG_RESOURCES] 
		WHERE  [PROFILE_ID] IN (0,@PROFILE_ID) AND [ACTIVE] = @ACTIVE_FLAG AND LTRIM(RTRIM([PLACEHOLDER_TYPE])) = @PLACEHOLDER_TYPE
		ORDER BY [SEQUENCE] ASC;

	OPEN CURSOR_PLACEHOLDER 
	FETCH NEXT FROM CURSOR_PLACEHOLDER INTO @PLACEHOLDER_NAME,@PLACEHOLDER;
	WHILE @@FETCH_STATUS = 0
		BEGIN

			SET @QUERY_GET_INPUT = REPLACE(@QUERY_GET_INPUT,concat('%',@PLACEHOLDER_NAME,'%'),ISNULL(@PLACEHOLDER,''));

			FETCH NEXT FROM CURSOR_PLACEHOLDER INTO @PLACEHOLDER_NAME,@PLACEHOLDER;
		END
	CLOSE CURSOR_PLACEHOLDER;
	DEALLOCATE CURSOR_PLACEHOLDER;
	-----------------------------------------------------------------------------------------------------------------------------------

	--======================================================-- Output result --======================================================--
	SET @RETURN_STATUS		= 0;
	SET @RETURN_STATUS_TEXT = concat('The final processed "@QUERY_GET_INPUT" query: ',char(13),@QUERY_GET_INPUT);
	SET @RETURN_ERROR_TEXT	= concat('','');

	PRINT '';
	PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
	-----------------------------------------------------------------------------------------------------------------------------------

	--===================================================-- Log result to table --===================================================--
	IF (@LOG_LEVEL in ('INFO')) BEGIN
		EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
								@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
								@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
								@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	--======================================================-- Safety checks --======================================================--
	EXEC [PRDEX_TEST_DYNAMIC_SQL]	@pQUERY			= @QUERY_GET_INPUT,
										@pRETURN_STATUS = 50051,
										@pQUERY_NAME	= N'@QUERY_GET_INPUT';
	-----------------------------------------------------------------------------------------------------------------------------------

	--==================================================-- run insert statement --===================================================--
	INSERT INTO @vTBDEX_IN([PROFILE_ID],[BATCH_ID],[REFERENCE1],[REFERENCE2],[REFERENCE3],[REFERENCE4],[REFERENCE5],
						   [EXTERNAL_REFERENCE1],[EXTERNAL_REFERENCE2],[EXTERNAL_REFERENCE3],[EXTERNAL_REFERENCE4],[EXTERNAL_REFERENCE5],
						   [TEST_MODE],[ASYNC_MODE],[COMMENT],[ADDED_WHO],[ADDED_WHEN])
	EXEC sp_executesql @QUERY_GET_INPUT;
	-----------------------------------------------------------------------------------------------------------------------------------

	--======================================================-- Output result --======================================================--
	SET @RETURN_STATUS		= 0;
	SET @RETURN_STATUS_TEXT = concat('Result saved to temp table!','');
	SET @RETURN_ERROR_TEXT	= concat('','');

	PRINT '';
	PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
	-----------------------------------------------------------------------------------------------------------------------------------

	--===================================================-- Log result to table --===================================================--
	IF (@LOG_LEVEL in ('INFO')) BEGIN
		EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
								@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
								@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
								@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
	END;
	----------------------------------------------------------------------------------------------------------------------------------

	--==========================================-- Count how many files are there now  --===========================================--
	SET @ROW_COUNT1 = ISNULL((SELECT count(*) FROM @vTBDEX_IN WHERE [PROFILE_ID] = @PROFILE_ID AND [BATCH_ID] = @BATCH_ID),0);
	IF (@ROW_COUNT1 < 1) BEGIN

		--====================================================-- exception / error --====================================================--
		SET @RETURN_STATUS		= 50002;
		SET @RETURN_STATUS_TEXT = concat('Maybe docs/data are already processed!?',char(13),					
									     '1. Check view [VWDEX_OUT]',char(13),							
									     '2. Check tables [TBDEX_IN] and [TBDEX_TMP_PROCESS]',char(13),	 
									     '3. Check the file status',char(13));
		SET @RETURN_ERROR_TEXT	= concat('','');

		PRINT 'WARN: ' + @RETURN_STATUS_TEXT;
		-----------------------------------------------------------------------------------------------------------------------------------

		--===================================================-- Log result to table --===================================================--
		IF (@LOG_LEVEL in ('INFO','WARN','ERROR')) BEGIN
			EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
									@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
									@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
									@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
		END;
		-----------------------------------------------------------------------------------------------------------------------------------

		RETURN @RETURN_STATUS;

	END; ELSE BEGIN

		--======================================================-- Output result --======================================================--
		SET @RETURN_STATUS		= 0;
		SET @RETURN_STATUS_TEXT = concat('Found: ',convert(nvarchar(100),@ROW_COUNT1),' data rows to process!');
		SET @RETURN_ERROR_TEXT	= concat('','');

		PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
		-----------------------------------------------------------------------------------------------------------------------------------

		--===================================================-- Log result to table --===================================================--
		IF (@LOG_LEVEL in ('INFO')) BEGIN
			EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
									@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
									@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
									@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
		END;
		-----------------------------------------------------------------------------------------------------------------------------------

	END;

	--========================================-- Print files which should be processed  --==========================================--

	BEGIN TRANSACTION;

		DECLARE CURSOR_INPUT CURSOR
		LOCAL FAST_FORWARD FOR 
			SELECT [REFERENCE1],[REFERENCE2],[REFERENCE3],[REFERENCE4],[REFERENCE5],
				   [EXTERNAL_REFERENCE1],[EXTERNAL_REFERENCE2],[EXTERNAL_REFERENCE3],[EXTERNAL_REFERENCE4],[EXTERNAL_REFERENCE5]
			FROM   @vTBDEX_IN
			WHERE  [PROFILE_ID] = @PROFILE_ID AND [BATCH_ID] = @BATCH_ID;

		OPEN CURSOR_INPUT 
		FETCH NEXT FROM CURSOR_INPUT INTO @REFERENCE1,@REFERENCE2,@REFERENCE3,@REFERENCE4,@REFERENCE5,@EXTERNAL_REFERENCE1,@EXTERNAL_REFERENCE2,@EXTERNAL_REFERENCE3,@EXTERNAL_REFERENCE4,@EXTERNAL_REFERENCE5;
		WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ROW_COUNTER_INPUT = @ROW_COUNTER_INPUT + 1;

				PRINT '' + char(13) + 'Processing data in BATCH_ID: ' + CONVERT(NVARCHAR(25),@BATCH_ID);
				PRINT 'REFERENCE1: ' + ISNULL(CONVERT(NVARCHAR(150),@REFERENCE1),'<NULL>');
				PRINT 'REFERENCE2: ' + ISNULL(CONVERT(NVARCHAR(150),@REFERENCE2),'<NULL>');
				PRINT 'REFERENCE3: ' + ISNULL(CONVERT(NVARCHAR(150),@REFERENCE3),'<NULL>');
				PRINT 'REFERENCE4: ' + ISNULL(CONVERT(NVARCHAR(150),@REFERENCE4),'<NULL>');
				PRINT 'REFERENCE5: ' + ISNULL(CONVERT(NVARCHAR(150),@REFERENCE5),'<NULL>');

				--=================================================-- Beginning safety check 1--=================================================--
				IF (SELECT count(*) 
					FROM  [TBDEX_IN] WITH (SNAPSHOT) 
					WHERE [PROFILE_ID] = @PROFILE_ID AND [BATCH_ID]   = @BATCH_ID 
					AND   ISNULL([REFERENCE1],'') = ISNULL(@REFERENCE1,'') AND ISNULL([REFERENCE2],'') = ISNULL(@REFERENCE2,'') 
					AND   ISNULL([REFERENCE3],'') = ISNULL(@REFERENCE3,'') AND ISNULL([REFERENCE4],'') = ISNULL(@REFERENCE4,'')
					AND   ISNULL([REFERENCE5],'') = ISNULL(@REFERENCE5,'') AND [ADDED_WHO] IN (@BATCH_CREATOR,@MY_PROCEDURE_NAME)
				) <> 0 BEGIN

					--======================================================-- Output result --======================================================--
					SET @RETURN_STATUS		= 0;
					SET @RETURN_STATUS_TEXT = concat('File is already in query ([TBDEX_IN])!','');
					SET @RETURN_ERROR_TEXT	= concat('','');

					PRINT 'WARN: ' + @RETURN_STATUS_TEXT;
					-----------------------------------------------------------------------------------------------------------------------------------
									
					--===================================================-- Log result to table --===================================================--
					IF (@LOG_LEVEL in ('INFO','WARN')) BEGIN
						EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
												@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
												@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
												@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
					END;
					-----------------------------------------------------------------------------------------------------------------------------------

				END; ELSE BEGIN

					IF (SELECT count(*) 
						FROM  [TBDEX_TMP_PROCESS] WITH (SNAPSHOT) 
						WHERE [PROFILE_ID]=@PROFILE_ID AND [BATCH_ID]=@BATCH_ID AND [ADDED_WHO] in (@BATCH_CREATOR,@MY_PROCEDURE_NAME)
					) <> 0 BEGIN

						--======================================================-- Output result --======================================================--
						SET @RETURN_STATUS		= 0;
						SET @RETURN_STATUS_TEXT = concat('File is already in query ([TBDEX_TMP_PROCESS])!','');
						SET @RETURN_ERROR_TEXT	= concat('','');

						PRINT 'WARN: ' + @RETURN_STATUS_TEXT;
						-----------------------------------------------------------------------------------------------------------------------------------
									
						--===================================================-- Log result to table --===================================================--
						IF (@LOG_LEVEL in ('INFO','WARN')) BEGIN
							EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
													@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
													@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
													@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
						END;
						-----------------------------------------------------------------------------------------------------------------------------------

					END; ELSE BEGIN
								
						-- if there is file wasnt already processes and exported
						IF (SELECT count(*) 
							FROM  [VWDEX_OUT] 
							WHERE [PROFILE_ID]=@PROFILE_ID AND ISNULL([REFERENCE1],'')=ISNULL(@REFERENCE1,'') AND ISNULL([REFERENCE2],'')=ISNULL(@REFERENCE2,'') AND ISNULL([REFERENCE3],'')=ISNULL(@REFERENCE3,'') AND ISNULL([REFERENCE4],'')=ISNULL(@REFERENCE4,'') AND ISNULL([REFERENCE5],'')=ISNULL(@REFERENCE5,'') 
						    AND   ISNULL([EXTERNAL_REFERENCE1],'')=ISNULL(@EXTERNAL_REFERENCE1,'') AND ISNULL([EXTERNAL_REFERENCE2],'')=ISNULL(@EXTERNAL_REFERENCE2,'') AND ISNULL([EXTERNAL_REFERENCE3],'')=ISNULL(@EXTERNAL_REFERENCE3,'') AND ISNULL([EXTERNAL_REFERENCE4],'')=ISNULL(@EXTERNAL_REFERENCE4,'') AND ISNULL([EXTERNAL_REFERENCE5],'')=ISNULL(@EXTERNAL_REFERENCE5,'')
						) = 0 BEGIN

							--======================================================-- Output result --======================================================--
							SET @RETURN_STATUS		= 0;
							SET @RETURN_STATUS_TEXT = concat('Inserting into table: [TBDEX_IN]...','');
							SET @RETURN_ERROR_TEXT	= concat('','');

							PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
							-----------------------------------------------------------------------------------------------------------------------------------
									
							--===================================================-- Log result to table --===================================================--
							IF (@LOG_LEVEL in ('INFO')) BEGIN
								EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
														@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
														@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
														@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
							END;
							-----------------------------------------------------------------------------------------------------------------------------------

							--==================================================-- run insert statement --===================================================--
							INSERT INTO [TBDEX_IN]([PROFILE_ID],[BATCH_ID],[REFERENCE1],[REFERENCE2],[REFERENCE3],[REFERENCE4],[REFERENCE5],
												   [EXTERNAL_REFERENCE1],[EXTERNAL_REFERENCE2],[EXTERNAL_REFERENCE3],[EXTERNAL_REFERENCE4],[EXTERNAL_REFERENCE5],
												   [TEST_MODE],[ASYNC_MODE],[COMMENT],[ADDED_WHO],[ADDED_WHEN])
							SELECT                 [PROFILE_ID],[BATCH_ID],[REFERENCE1],[REFERENCE2],[REFERENCE3],[REFERENCE4],[REFERENCE5],
												   [EXTERNAL_REFERENCE1],[EXTERNAL_REFERENCE2],[EXTERNAL_REFERENCE3],[EXTERNAL_REFERENCE4],[EXTERNAL_REFERENCE5],
												   [TEST_MODE],[ASYNC_MODE],[COMMENT],[ADDED_WHO],[ADDED_WHEN]
							FROM @vTBDEX_IN
							WHERE [PROFILE_ID] = @PROFILE_ID
							AND   [BATCH_ID] = @BATCH_ID
							AND   ISNULL([REFERENCE1],'') = ISNULL(@REFERENCE1,'')
							AND   ISNULL([REFERENCE2],'') = ISNULL(@REFERENCE2,'')
							AND   ISNULL([REFERENCE3],'') = ISNULL(@REFERENCE3,'')
							AND   ISNULL([REFERENCE4],'') = ISNULL(@REFERENCE4,'')
							AND   ISNULL([REFERENCE5],'') = ISNULL(@REFERENCE5,'')
							AND   ISNULL([EXTERNAL_REFERENCE1],'') = ISNULL(@EXTERNAL_REFERENCE1,'')
							AND   ISNULL([EXTERNAL_REFERENCE2],'') = ISNULL(@EXTERNAL_REFERENCE2,'')
							AND   ISNULL([EXTERNAL_REFERENCE3],'') = ISNULL(@EXTERNAL_REFERENCE3,'')
							AND   ISNULL([EXTERNAL_REFERENCE4],'') = ISNULL(@EXTERNAL_REFERENCE4,'')
							AND   ISNULL([EXTERNAL_REFERENCE5],'') = ISNULL(@EXTERNAL_REFERENCE5,'')
							-----------------------------------------------------------------------------------------------------------------------------------

							--======================================================-- Output result --======================================================--
							SET @RETURN_STATUS		= 0;
							SET @RETURN_STATUS_TEXT = concat('Insert into [TBDEX_IN] done!','');
							SET @RETURN_ERROR_TEXT	= concat('','');

							PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
							-----------------------------------------------------------------------------------------------------------------------------------
									
							--===================================================-- Log result to table --===================================================--
							IF (@LOG_LEVEL in ('INFO')) BEGIN
								EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
														@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
														@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
														@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
							END;
							-----------------------------------------------------------------------------------------------------------------------------------

						END; ELSE BEGIN

							IF (@FORCE = 0) BEGIN

								--======================================================-- Output result --======================================================--
								SET @RETURN_STATUS		= 0;
								SET @RETURN_STATUS_TEXT = concat('File was already exported ([TBDEX_OUT]), deleting from current call!','');
								SET @RETURN_ERROR_TEXT	= concat('','');

								PRINT 'WARN: ' + @RETURN_STATUS_TEXT;
								-----------------------------------------------------------------------------------------------------------------------------------
									
								--===================================================-- Log result to table --===================================================--
								IF (@LOG_LEVEL in ('INFO','WARN')) BEGIN
									EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
															@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
															@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
															@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
								END;
								-----------------------------------------------------------------------------------------------------------------------------------

							END; ELSE BEGIN

								--======================================================-- Output result --======================================================--
								SET @RETURN_STATUS		= 0;
								SET @RETURN_STATUS_TEXT = concat('File was already exported ([TBDEX_OUT]), forcing export again!','');
								SET @RETURN_ERROR_TEXT	= concat('','');

								PRINT 'WARN: ' + @RETURN_STATUS_TEXT;
								-----------------------------------------------------------------------------------------------------------------------------------
									
								--===================================================-- Log result to table --===================================================--
								IF (@LOG_LEVEL in ('INFO','WARN')) BEGIN
									EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
															@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
															@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
															@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
								END;
								-----------------------------------------------------------------------------------------------------------------------------------
									
								--==================================================-- run insert statement --===================================================--
								INSERT INTO [TBDEX_IN]([PROFILE_ID],[BATCH_ID],[REFERENCE1],[REFERENCE2],[REFERENCE3],[REFERENCE4],[REFERENCE5],
								                       [EXTERNAL_REFERENCE1],[EXTERNAL_REFERENCE2],[EXTERNAL_REFERENCE3],[EXTERNAL_REFERENCE4],[EXTERNAL_REFERENCE5],
													   [TEST_MODE],[ASYNC_MODE],[COMMENT],[ADDED_WHO],[ADDED_WHEN])
    							SELECT                 [PROFILE_ID],[BATCH_ID],[REFERENCE1],[REFERENCE2],[REFERENCE3],[REFERENCE4],[REFERENCE5],
													   [EXTERNAL_REFERENCE1],[EXTERNAL_REFERENCE2],[EXTERNAL_REFERENCE3],[EXTERNAL_REFERENCE4],[EXTERNAL_REFERENCE5],
													   [TEST_MODE],[ASYNC_MODE],concat('Forced export!;',ISNULL([COMMENT],'')),[ADDED_WHO],[ADDED_WHEN]
								FROM @vTBDEX_IN
								WHERE [PROFILE_ID] = @PROFILE_ID
								AND   [BATCH_ID] = @BATCH_ID
								AND   ISNULL([REFERENCE1],'') = ISNULL(@REFERENCE1,'')
								AND   ISNULL([REFERENCE2],'') = ISNULL(@REFERENCE2,'')
								AND   ISNULL([REFERENCE3],'') = ISNULL(@REFERENCE3,'')
								AND   ISNULL([REFERENCE4],'') = ISNULL(@REFERENCE4,'')
								AND   ISNULL([REFERENCE5],'') = ISNULL(@REFERENCE5,'')
								AND   ISNULL([EXTERNAL_REFERENCE1],'') = ISNULL(@EXTERNAL_REFERENCE1,'')
								AND   ISNULL([EXTERNAL_REFERENCE2],'') = ISNULL(@EXTERNAL_REFERENCE2,'')
								AND   ISNULL([EXTERNAL_REFERENCE3],'') = ISNULL(@EXTERNAL_REFERENCE3,'')
								AND   ISNULL([EXTERNAL_REFERENCE4],'') = ISNULL(@EXTERNAL_REFERENCE4,'')
								AND   ISNULL([EXTERNAL_REFERENCE5],'') = ISNULL(@EXTERNAL_REFERENCE5,'')
								-----------------------------------------------------------------------------------------------------------------------------------
							END;

						END;

					END;

				END; -- End safety check 1
				-----------------------------------------------------------------------------------------------------------------------------------


				--=================================================-- Beginning safety check 2--=================================================--
				IF (SELECT count(*) 
					FROM  [TBDEX_TMP_PROCESS_REFERENCES] WITH (SNAPSHOT) 
					WHERE [PROFILE_ID] = @PROFILE_ID AND [BATCH_ID]   = @BATCH_ID 
					AND   ISNULL([REFERENCE1],'') = ISNULL(@REFERENCE1,'') AND ISNULL([REFERENCE2],'') = ISNULL(@REFERENCE2,'') 
					AND   ISNULL([REFERENCE3],'') = ISNULL(@REFERENCE3,'') AND ISNULL([REFERENCE4],'') = ISNULL(@REFERENCE4,'')
					AND   ISNULL([REFERENCE5],'') = ISNULL(@REFERENCE5,'') AND [ADDED_WHO] IN (@BATCH_CREATOR,@MY_PROCEDURE_NAME)
				) <> 0 BEGIN

					--======================================================-- Output result --======================================================--
					SET @RETURN_STATUS		= 0;
					SET @RETURN_STATUS_TEXT = concat('File is already in query ([TBDEX_TMP_PROCESS_REFERENCES])!','');
					SET @RETURN_ERROR_TEXT	= concat('','');

					PRINT 'WARN: ' + @RETURN_STATUS_TEXT;
					-----------------------------------------------------------------------------------------------------------------------------------
									
					--===================================================-- Log result to table --===================================================--
					IF (@LOG_LEVEL in ('INFO','WARN')) BEGIN
						EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
												@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
												@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
												@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
					END;
					-----------------------------------------------------------------------------------------------------------------------------------

				END; ELSE BEGIN

					IF (SELECT count(*) FROM [TBDEX_TMP_PROCESS] WITH (SNAPSHOT) WHERE [PROFILE_ID]=@PROFILE_ID AND [BATCH_ID]=@BATCH_ID AND [ADDED_WHO]=@MY_PROCEDURE_NAME) <> 0 BEGIN

						--======================================================-- Output result --======================================================--
						SET @RETURN_STATUS		= 0;
						SET @RETURN_STATUS_TEXT = concat('File is already in query ([TBDEX_TMP_PROCESS])!','');
						SET @RETURN_ERROR_TEXT	= concat('','');

						PRINT 'WARN: ' + @RETURN_STATUS_TEXT;
						-----------------------------------------------------------------------------------------------------------------------------------
									
						--===================================================-- Log result to table --===================================================--
						IF (@LOG_LEVEL in ('INFO','WARN')) BEGIN
							EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
													@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
													@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
													@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
						END;
						-----------------------------------------------------------------------------------------------------------------------------------

					END; ELSE BEGIN
								
						-- if there is file wasnt already processes and exported
						IF (SELECT count(*) 
							FROM  [VWDEX_OUT] 
							WHERE [PROFILE_ID]=@PROFILE_ID AND ISNULL([REFERENCE1],'')=ISNULL(@REFERENCE1,'') AND ISNULL([REFERENCE2],'')=ISNULL(@REFERENCE2,'') AND ISNULL([REFERENCE3],'')=ISNULL(@REFERENCE3,'') AND ISNULL([REFERENCE4],'')=ISNULL(@REFERENCE4,'') AND ISNULL([REFERENCE5],'')=ISNULL(@REFERENCE5,'') 
						    AND   ISNULL([EXTERNAL_REFERENCE1],'')=ISNULL(@EXTERNAL_REFERENCE1,'') AND ISNULL([EXTERNAL_REFERENCE2],'')=ISNULL(@EXTERNAL_REFERENCE2,'') AND ISNULL([EXTERNAL_REFERENCE3],'')=ISNULL(@EXTERNAL_REFERENCE3,'') AND ISNULL([EXTERNAL_REFERENCE4],'')=ISNULL(@EXTERNAL_REFERENCE4,'') AND ISNULL([EXTERNAL_REFERENCE5],'')=ISNULL(@EXTERNAL_REFERENCE5,'')
						) = 0 BEGIN

							--======================================================-- Output result --======================================================--
							SET @RETURN_STATUS		= 0;
							SET @RETURN_STATUS_TEXT = concat('Inserting into table: [TBDEX_TMP_PROCESS_REFERENCES]...','');
							SET @RETURN_ERROR_TEXT	= concat('','');

							PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
							-----------------------------------------------------------------------------------------------------------------------------------
									
							--===================================================-- Log result to table --===================================================--
							IF (@LOG_LEVEL in ('INFO')) BEGIN
								EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
														@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
														@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
														@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
							END;
							-----------------------------------------------------------------------------------------------------------------------------------

							--==================================================-- run insert statement --===================================================--
							INSERT INTO [TBDEX_TMP_PROCESS_REFERENCES]([PROFILE_ID],[BATCH_ID],[REFERENCE1],[REFERENCE2],[REFERENCE3],[REFERENCE4],[REFERENCE5],
							                                           [EXTERNAL_REFERENCE1],[EXTERNAL_REFERENCE2],[EXTERNAL_REFERENCE3],[EXTERNAL_REFERENCE4],[EXTERNAL_REFERENCE5],
																	   [COMMENT],[ADDED_WHO],[ADDED_WHEN])
							SELECT                                     [PROFILE_ID],[BATCH_ID],[REFERENCE1],[REFERENCE2],[REFERENCE3],[REFERENCE4],[REFERENCE5],
							                                           [EXTERNAL_REFERENCE1],[EXTERNAL_REFERENCE2],[EXTERNAL_REFERENCE3],[EXTERNAL_REFERENCE4],[EXTERNAL_REFERENCE5],
																	   [COMMENT],[ADDED_WHO],[ADDED_WHEN]
							FROM @vTBDEX_IN
							WHERE [PROFILE_ID] = @PROFILE_ID
							AND   [BATCH_ID] = @BATCH_ID
							AND   ISNULL([REFERENCE1],'') = ISNULL(@REFERENCE1,'')
							AND   ISNULL([REFERENCE2],'') = ISNULL(@REFERENCE2,'')
							AND   ISNULL([REFERENCE3],'') = ISNULL(@REFERENCE3,'')
							AND   ISNULL([REFERENCE4],'') = ISNULL(@REFERENCE4,'')
							AND   ISNULL([REFERENCE5],'') = ISNULL(@REFERENCE5,'')
							AND   ISNULL([EXTERNAL_REFERENCE1],'') = ISNULL(@EXTERNAL_REFERENCE1,'')
							AND   ISNULL([EXTERNAL_REFERENCE2],'') = ISNULL(@EXTERNAL_REFERENCE2,'')
							AND   ISNULL([EXTERNAL_REFERENCE3],'') = ISNULL(@EXTERNAL_REFERENCE3,'')
							AND   ISNULL([EXTERNAL_REFERENCE4],'') = ISNULL(@EXTERNAL_REFERENCE4,'')
							AND   ISNULL([EXTERNAL_REFERENCE5],'') = ISNULL(@EXTERNAL_REFERENCE5,'')
							-----------------------------------------------------------------------------------------------------------------------------------
							
							--======================================================-- Output result --======================================================--
							SET @RETURN_STATUS		= 0;
							SET @RETURN_STATUS_TEXT = concat('Insert into [TBDEX_TMP_PROCESS_REFERENCES] done!','');
							SET @RETURN_ERROR_TEXT	= concat('','');

							PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
							-----------------------------------------------------------------------------------------------------------------------------------
									
							--===================================================-- Log result to table --===================================================--
							IF (@LOG_LEVEL in ('INFO')) BEGIN
								EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
														@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
														@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
														@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
							END;
							-----------------------------------------------------------------------------------------------------------------------------------

						END; ELSE BEGIN

							IF (@FORCE = 0) BEGIN

								--======================================================-- Output result --======================================================--
								SET @RETURN_STATUS		= 0;
								SET @RETURN_STATUS_TEXT = concat('File was already exported ([TBDEX_OUT]), deleting from current call!','');
								SET @RETURN_ERROR_TEXT	= concat('','');

								PRINT 'WARN: ' + @RETURN_STATUS_TEXT;
								-----------------------------------------------------------------------------------------------------------------------------------
									
								--===================================================-- Log result to table --===================================================--
								IF (@LOG_LEVEL in ('INFO','WARN')) BEGIN
									EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
															@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
															@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
															@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
								END;
								-----------------------------------------------------------------------------------------------------------------------------------

							END; ELSE BEGIN

								--======================================================-- Output result --======================================================--
								SET @RETURN_STATUS		= 0;
								SET @RETURN_STATUS_TEXT = concat('File was already exported ([TBDEX_OUT]), forcing export again!','');
								SET @RETURN_ERROR_TEXT	= concat('','');

								PRINT 'WARN: ' + @RETURN_STATUS_TEXT;
								-----------------------------------------------------------------------------------------------------------------------------------
									
								--===================================================-- Log result to table --===================================================--
								IF (@LOG_LEVEL in ('INFO','WARN')) BEGIN
									EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
															@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
															@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
															@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
								END;
								-----------------------------------------------------------------------------------------------------------------------------------
									
								--==================================================-- run insert statement --===================================================--
								INSERT INTO [TBDEX_TMP_PROCESS_REFERENCES]([PROFILE_ID],[BATCH_ID],[REFERENCE1],[REFERENCE2],[REFERENCE3],[REFERENCE4],[REFERENCE5],
																		   [EXTERNAL_REFERENCE1],[EXTERNAL_REFERENCE2],[EXTERNAL_REFERENCE3],[EXTERNAL_REFERENCE4],[EXTERNAL_REFERENCE5],
																		   [COMMENT],[ADDED_WHO],[ADDED_WHEN])
    							SELECT                                     [PROFILE_ID],[BATCH_ID],[REFERENCE1],[REFERENCE2],[REFERENCE3],[REFERENCE4],[REFERENCE5],
								                                           [EXTERNAL_REFERENCE1],[EXTERNAL_REFERENCE2],[EXTERNAL_REFERENCE3],[EXTERNAL_REFERENCE4],[EXTERNAL_REFERENCE5],
																		   concat('Forced export!;',ISNULL([COMMENT],'')),[ADDED_WHO],[ADDED_WHEN]
								FROM @vTBDEX_IN
								WHERE [PROFILE_ID] = @PROFILE_ID
								AND   [BATCH_ID] = @BATCH_ID
								AND   ISNULL([REFERENCE1],'') = ISNULL(@REFERENCE1,'')
								AND   ISNULL([REFERENCE2],'') = ISNULL(@REFERENCE2,'')
								AND   ISNULL([REFERENCE3],'') = ISNULL(@REFERENCE3,'')
								AND   ISNULL([REFERENCE4],'') = ISNULL(@REFERENCE4,'')
								AND   ISNULL([REFERENCE5],'') = ISNULL(@REFERENCE5,'')
								AND   ISNULL([EXTERNAL_REFERENCE1],'') = ISNULL(@EXTERNAL_REFERENCE1,'')
								AND   ISNULL([EXTERNAL_REFERENCE2],'') = ISNULL(@EXTERNAL_REFERENCE2,'')
								AND   ISNULL([EXTERNAL_REFERENCE3],'') = ISNULL(@EXTERNAL_REFERENCE3,'')
								AND   ISNULL([EXTERNAL_REFERENCE4],'') = ISNULL(@EXTERNAL_REFERENCE4,'')
								AND   ISNULL([EXTERNAL_REFERENCE5],'') = ISNULL(@EXTERNAL_REFERENCE5,'')
								-----------------------------------------------------------------------------------------------------------------------------------
							END;

						END;

					END;

				END; -- End safety check 2
				-----------------------------------------------------------------------------------------------------------------------------------

				FETCH NEXT FROM CURSOR_INPUT INTO @REFERENCE1,@REFERENCE2,@REFERENCE3,@REFERENCE4,@REFERENCE5,@EXTERNAL_REFERENCE1,@EXTERNAL_REFERENCE2,@EXTERNAL_REFERENCE3,@EXTERNAL_REFERENCE4,@EXTERNAL_REFERENCE5;
			END
		CLOSE CURSOR_INPUT;
		DEALLOCATE CURSOR_INPUT;


	--===============================================-- Prepare dynamic export table --==============================================--
	SET @TBDEX_TMP_TABLE_SCHEMA_AND_NAME =	CASE 
											 WHEN (LEN(LTRIM(RTRIM(@TBDEX_TMP_TABLE_SCHEMA))) > 0) AND (LEFT(@TBDEX_TMP_TABLE_NAME,1) <> '#')
											 THEN QUOTENAME(@TBDEX_TMP_TABLE_SCHEMA) + '.' + QUOTENAME(@TBDEX_TMP_TABLE_NAME)
											 ELSE @TBDEX_TMP_TABLE_NAME
											END;
	
	SET @TBDEX_TMP_TABLE_DROP_QUERY		 =	'SET ANSI_NULLS ON;
											SET QUOTED_IDENTIFIER ON;
											IF OBJECT_ID(''' + 'tempdb..' + @TBDEX_TMP_TABLE_SCHEMA_AND_NAME + ''',''U'') IS NOT NULL
											DROP TABLE   ' + 'tempdb..' + @TBDEX_TMP_TABLE_SCHEMA_AND_NAME + ';'
	
	SET @TBDEX_TMP_TABLE_COLUMNS	     =	(SELECT STUFF((SELECT CONCAT(', ',QUOTENAME(REPLACE(REPLACE(ISNULL([COS].[PATH_OR_COLUMN],''),',','_'),'-','_')),' ')
											FROM  [TBDEX_CFG_OUT_STRUCTURE] AS [COS]
											WHERE [COS].[ACTIVE] = @ACTIVE_FLAG AND [COS].[EXPORT_TYPE] = @EXPORT_TYPE AND [COS].[PROFILE_ID] = @PROFILE_ID 
											AND   [COS].[LANGUAGE] in (REPLACE(@LANGUAGE,'-','_'),REPLACE(@LANGUAGE,'_','-'))
											ORDER BY [COS].[SEQUENCE] ASC
											FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,2,''));

	SET @TBDEX_TMP_TABLE_COLUMNS		 =	REPLACE(concat(
											'[PROFILE_ID], ',
											'[BATCH_ID], ',
											@TBDEX_TMP_TABLE_COLUMNS),',,',',');

	SET @TBDEX_TMP_TABLE_CREATE_QUERY	 =	(SELECT STUFF((SELECT CONCAT(', ',QUOTENAME(REPLACE(REPLACE(ISNULL([COS].[PATH_OR_COLUMN],''),',','_'),'-','_')),' ',
	                                        LTRIM(RTRIM(ISNULL([COS].[DATA_TYPE],'NVARCHAR(100)'))))
											FROM  [TBDEX_CFG_OUT_STRUCTURE] AS [COS]
											WHERE [COS].[ACTIVE] = @ACTIVE_FLAG AND [COS].[EXPORT_TYPE] = @EXPORT_TYPE AND [COS].[PROFILE_ID] = @PROFILE_ID 
											AND   [COS].[LANGUAGE] in (REPLACE(@LANGUAGE,'-','_'),REPLACE(@LANGUAGE,'_','-'))
											ORDER BY [COS].[SEQUENCE] ASC
											FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,2,''));

	SET @TBDEX_TMP_TABLE_CREATE_QUERY    =	REPLACE(concat(
											'[GUID]       [bigint] IDENTITY(1,1) NOT NULL, ',
											'[PROFILE_ID] [bigint] NOT NULL, ',
											'[BATCH_ID]   [nvarchar](25) NOT NULL, ',
											@TBDEX_TMP_TABLE_CREATE_QUERY),',,',',');
	--MEMORY_OPTIMIZED dont work if data comes from a other db
	--SET @TBDEX_TMP_TABLE_CREATE_QUERY	 =	'SET ANSI_NULLS ON;
	--										SET QUOTED_IDENTIFIER ON;
	--										CREATE TABLE ' + @TBDEX_TMP_TABLE_SCHEMA_AND_NAME + '
	--										(' + @TBDEX_TMP_TABLE_CREATE_QUERY + ',
	--										 CONSTRAINT [PK_'+ @TBDEX_TMP_TABLE_NAME +']  PRIMARY KEY NONCLUSTERED 
	--										([GUID] ASC)
	--										) WITH ( MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_ONLY );';

	SET @TBDEX_TMP_TABLE_CREATE_QUERY	 =	'SET ANSI_NULLS ON;
											SET QUOTED_IDENTIFIER ON;
											CREATE TABLE ' + @TBDEX_TMP_TABLE_SCHEMA_AND_NAME + '
											(' + @TBDEX_TMP_TABLE_CREATE_QUERY + ');';

	SET @TBDEX_TMP_TABLE_DROP_QUERY		 =	REPLACE(@TBDEX_TMP_TABLE_DROP_QUERY,', ,',',');
	SET @TBDEX_TMP_TABLE_COLUMNS		 =	REPLACE(@TBDEX_TMP_TABLE_COLUMNS,', ,',',');
	SET @TBDEX_TMP_TABLE_CREATE_QUERY	 =	REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,', ,',',');
	-----------------------------------------------------------------------------------------------------------------------------------


	--==================================================-- Handle placeholders  --==================================================--
	PRINT '';
	PRINT 'Replacing placeholders...';
		
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%PROFILE_ID%',ISNULL(@PROFILE_ID,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%TEST_MODE%',ISNULL(@TEST_MODE,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%ASYNC_MODE%',ISNULL(@ASYNC_MODE,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%BATCH_ID%',ISNULL(@BATCH_ID,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%BATCH_CREATOR%',ISNULL(@BATCH_CREATOR,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%LANGUAGE%',ISNULL(@LANGUAGE,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%LOG_LEVEL%',ISNULL(@LOG_LEVEL,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%START_QUERY%',ISNULL(@START_QUERY,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%START_QUERY_VAR1%',ISNULL(@START_QUERY_VAR1,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%START_QUERY_VAR2%',ISNULL(@START_QUERY_VAR2,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%START_QUERY_VAR3%',ISNULL(@START_QUERY_VAR3,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%START_QUERY_VAR4%',ISNULL(@START_QUERY_VAR4,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%START_QUERY_VAR5%',ISNULL(@START_QUERY_VAR5,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%FORCE%',ISNULL(@FORCE,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%MY_PROCEDURE_NAME%',ISNULL(@MY_PROCEDURE_NAME,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%PROFILE_NAME%',ISNULL(@PROFILE_NAME,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%MANDANTOR%',ISNULL(@MANDANTOR,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%EXPORT_TYPE%',ISNULL(@EXPORT_TYPE,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%REFERENCE1%',ISNULL(@REFERENCE1,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%REFERENCE2%',ISNULL(@REFERENCE2,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%REFERENCE3%',ISNULL(@REFERENCE3,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%REFERENCE4%',ISNULL(@REFERENCE4,''));
	SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,'%REFERENCE5%',ISNULL(@REFERENCE5,''));

	DECLARE CURSOR_PLACEHOLDER CURSOR
	LOCAL FAST_FORWARD FOR 
		SELECT [PLACEHOLDER_NAME] as 'Placeholder_Name', [PLACEHOLDER] as 'Placeholder'
		FROM   [TBDEX_CFG_RESOURCES] 
		WHERE  [PROFILE_ID] IN (0,@PROFILE_ID) AND [ACTIVE] = @ACTIVE_FLAG AND LTRIM(RTRIM([PLACEHOLDER_TYPE])) = @PLACEHOLDER_TYPE
		ORDER BY [SEQUENCE] ASC;

	OPEN CURSOR_PLACEHOLDER 
	FETCH NEXT FROM CURSOR_PLACEHOLDER INTO @PLACEHOLDER_NAME,@PLACEHOLDER;
	WHILE @@FETCH_STATUS = 0
		BEGIN

			SET @TBDEX_TMP_TABLE_CREATE_QUERY = REPLACE(@TBDEX_TMP_TABLE_CREATE_QUERY,concat('%',@PLACEHOLDER_NAME,'%'),ISNULL(@PLACEHOLDER,''));

			FETCH NEXT FROM CURSOR_PLACEHOLDER INTO @PLACEHOLDER_NAME,@PLACEHOLDER;
		END
	CLOSE CURSOR_PLACEHOLDER;
	DEALLOCATE CURSOR_PLACEHOLDER;
	-----------------------------------------------------------------------------------------------------------------------------------

	--======================================================-- Output result --======================================================--
	SET @RETURN_STATUS		= 0;
	SET @RETURN_STATUS_TEXT = concat('The complete "@TBDEX_TMP_TABLE_CREATE_QUERY" query: ',char(13),@TBDEX_TMP_TABLE_CREATE_QUERY);
	SET @RETURN_ERROR_TEXT	= concat('','');

	PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
	-----------------------------------------------------------------------------------------------------------------------------------
	
	--===================================================-- Log result to table --===================================================--
	IF (@LOG_LEVEL in ('INFO')) BEGIN
		EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
								@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
								@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
								@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
	END;
	-----------------------------------------------------------------------------------------------------------------------------------


	--===================================================-- Update process table --==================================================--
	UPDATE  [TBDEX_TMP_PROCESS]
	SET		[TBDEX_TMP_TABLE_SCHEMA]			= @TBDEX_TMP_TABLE_SCHEMA,
			[TBDEX_TMP_TABLE_NAME]				= @TBDEX_TMP_TABLE_NAME,
			[TBDEX_TMP_TABLE_SCHEMA_AND_NAME]	= @TBDEX_TMP_TABLE_SCHEMA_AND_NAME,
			[TBDEX_TMP_TABLE_COLUMNS]			= @TBDEX_TMP_TABLE_COLUMNS,
			[TBDEX_TMP_TABLE_DROP_QUERY]		= @TBDEX_TMP_TABLE_DROP_QUERY,
			[TBDEX_TMP_TABLE_CREATE_QUERY]		= @TBDEX_TMP_TABLE_CREATE_QUERY,
			[CHANGED_WHO]						= @BATCH_CREATOR,
			[CHANGED_WHEN]						= GetDate()
	WHERE	[PROFILE_ID]						= @PROFILE_ID
	AND		[BATCH_ID]							= @BATCH_ID
	AND		[ADDED_WHO]							= @BATCH_CREATOR
	-----------------------------------------------------------------------------------------------------------------------------------


	--===================================================-- COMMIT TRANSACTION --====================================================--
	IF (@@TRANCOUNT > 0) BEGIN
		COMMIT TRANSACTION;
	END;
	-----------------------------------------------------------------------------------------------------------------------------------


	--======================================================-- Cleaning up  --======================================================--
	IF (@TEST_MODE = 1) BEGIN

		--======================================================-- Output result --======================================================--
		SET @RETURN_STATUS		= 0;
		SET @RETURN_STATUS_TEXT = concat('Showing content of table [TBDEX_IN] before cleanup','');
		SET @RETURN_ERROR_TEXT	= concat('','');

		PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
		-----------------------------------------------------------------------------------------------------------------------------------

		--=====================================================-- Showing result --======================================================--
		SELECT	 [GUID],
				 [PROFILE_ID],
				 [BATCH_ID],
				 [REFERENCE1],
				 [REFERENCE2],
				 [REFERENCE3],
				 [REFERENCE4],
				 [REFERENCE5],
				 [EXTERNAL_REFERENCE1],
				 [EXTERNAL_REFERENCE2],
				 [EXTERNAL_REFERENCE3],
				 [EXTERNAL_REFERENCE4],
				 [EXTERNAL_REFERENCE5],
				 [TEST_MODE],
				 [ASYNC_MODE],
				 [COMMENT],
				 [ADDED_WHO],
				 [ADDED_WHEN]
		FROM [TBDEX_IN] WITH (SNAPSHOT)-- In test mode show result AND DO NOT use dirty reads.
		WHERE [PROFILE_ID] = @PROFILE_ID AND [BATCH_ID] = @BATCH_ID AND [TEST_MODE] = @TEST_MODE 
		AND   [ASYNC_MODE] = @ASYNC_MODE AND [ADDED_WHO] IN (@BATCH_CREATOR,@MY_PROCEDURE_NAME);
		-----------------------------------------------------------------------------------------------------------------------------------

		--======================================================-- Output result --======================================================--
		SET @RETURN_STATUS		= 0;
		SET @RETURN_STATUS_TEXT = concat('Cleaning up Query table because of TEST_MODE is enabled!','');
		SET @RETURN_ERROR_TEXT	= concat('','');

		PRINT 'WARN: ' + @RETURN_STATUS_TEXT;
		-----------------------------------------------------------------------------------------------------------------------------------

		--===================================================-- Log result to table --===================================================--
		IF (@LOG_LEVEL in ('INFO','WARN')) BEGIN
			EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
									@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
									@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
									@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
		END;
		-----------------------------------------------------------------------------------------------------------------------------------

		--=======================================================-- Cleaning up --=======================================================--
		DELETE FROM [TBDEX_IN]
		WHERE [PROFILE_ID] = @PROFILE_ID AND [BATCH_ID] = @BATCH_ID AND [TEST_MODE] = @TEST_MODE 
		AND   [ASYNC_MODE] = @ASYNC_MODE AND [ADDED_WHO] IN (@BATCH_CREATOR,@MY_PROCEDURE_NAME);
		-----------------------------------------------------------------------------------------------------------------------------------

	END; ELSE BEGIN

		--======================================================-- Output result --======================================================--
		SET @RETURN_STATUS		= 0;
		SET @RETURN_STATUS_TEXT = concat('Dont cleaning up Query table because of TEST_MODE is disabled!','');
		SET @RETURN_ERROR_TEXT	= concat('','');

		PRINT '';
		PRINT 'INFO: ' + @RETURN_STATUS_TEXT;
		-----------------------------------------------------------------------------------------------------------------------------------

		--===================================================-- Log result to table --===================================================--
		IF (@LOG_LEVEL in ('INFO','WARN')) BEGIN
			EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'WARN',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
									@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
									@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
									@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
		END;
		-----------------------------------------------------------------------------------------------------------------------------------

	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	--======================================================-- Output result --======================================================--
	SET @RETURN_STATUS		= 0;
	SET @RETURN_STATUS_TEXT = concat('END PROCEDURE [',@MY_PROCEDURE_NAME,'] @ ',CONVERT(NVARCHAR(50),GETDATE(),120));
	SET @RETURN_ERROR_TEXT	= concat('','');

	PRINT char(13) + @RETURN_STATUS_TEXT;
	PRINT '====================================================================================================';
	-----------------------------------------------------------------------------------------------------------------------------------

	--===================================================-- Log result to table --===================================================--
	IF (@LOG_LEVEL in ('INFO')) BEGIN
		EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'INFO',				@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
								@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
								@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
								@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	RETURN @RETURN_STATUS;

END TRY BEGIN CATCH

	--====================================================-- exception / error --====================================================--
	IF (@@TRANCOUNT > 0) BEGIN
		ROLLBACK TRANSACTION;
	END;

	PRINT char(13) + 'ERROR: ' + @RETURN_STATUS_TEXT + '; ' + @RETURN_ERROR_TEXT;
	-----------------------------------------------------------------------------------------------------------------------------------

	--===================================================-- Log result to table --===================================================--
	IF (@LOG_LEVEL in ('INFO','WARN','ERROR')) BEGIN
		EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'ERROR',			@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
								@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
								@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
								@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	--======================================================-- Output result --======================================================--
	SET @RETURN_STATUS		= CASE WHEN @RETURN_STATUS > 50000 THEN @RETURN_STATUS ELSE 50000 END;
	SET @RETURN_STATUS_TEXT = concat(char(13),'END PROCEDURE [',@MY_PROCEDURE_NAME,'] @ ',CONVERT(NVARCHAR(50),GETDATE(),120));
	SET @RETURN_ERROR_TEXT	= concat('ERROR MESSAGE: ',CONVERT(NVARCHAR(500),ERROR_MESSAGE()));

	PRINT 'ERROR IN PROCEDURE: [' + @MY_PROCEDURE_NAME + ']' + char(13) + @RETURN_ERROR_TEXT;
	PRINT @RETURN_STATUS_TEXT;
	PRINT '====================================================================================================';
	-----------------------------------------------------------------------------------------------------------------------------------

	--===================================================-- Log result to table --===================================================--
	IF (@LOG_LEVEL in ('INFO','WARN','ERROR')) BEGIN
		EXEC [PRDEX_WRITE_LOG]	@pLOG_LEVEL	 = N'ERROR',			@pPROFILE_ID	= @PROFILE_ID,			@pBATCH_ID		= @BATCH_ID,
								@pREFERENCE1 = @REFERENCE1,			@pREFERENCE2	= @REFERENCE2,			@pREFERENCE3	= @REFERENCE3,
								@pREFERENCE4 = @REFERENCE4,			@pREFERENCE5	= @REFERENCE5,			@pRETURN_CODE	= @RETURN_STATUS,
								@pMESSAGE1	 = @RETURN_STATUS_TEXT, @pMESSAGE2		= @RETURN_ERROR_TEXT,	@pADDED_WHO		= @MY_PROCEDURE_NAME;
	END;
	-----------------------------------------------------------------------------------------------------------------------------------

	RETURN @RETURN_STATUS;

END CATCH;
GO