SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- [PRDEX_RUN_MAINPROCESSING]
-- =================================================================
-- Sub procedure to run MAINPROCESSING steps
-- 
-- Returns: INTEGER; 0 = ok; 0 <> not 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_RUN_MAINPROCESSING](
	@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),
	@pMAIN_QUERY						NVARCHAR(MAX),
	@pMAIN_QUERY_VAR1					NVARCHAR(50),
	@pMAIN_QUERY_VAR2					NVARCHAR(50),
	@pMAIN_QUERY_VAR3					NVARCHAR(50),
	@pMAIN_QUERY_VAR4					NVARCHAR(50),
	@pMAIN_QUERY_VAR5					NVARCHAR(50),
	@pEND_QUERY							NVARCHAR(MAX),
	@pEND_QUERY_VAR1					NVARCHAR(50),
	@pEND_QUERY_VAR2					NVARCHAR(50),
	@pEND_QUERY_VAR3					NVARCHAR(50),
	@pEND_QUERY_VAR4					NVARCHAR(50),
	@pEND_QUERY_VAR5					NVARCHAR(50),
	@pFORCE								BIT,
	@pPROFILE_NAME						NVARCHAR(50),
	@pMANDANTOR							NVARCHAR(50),
	@pEXPORT_TYPE						NVARCHAR(50),
	@pDEFAULT_DATA_SEPARATOR			NVARCHAR(10),
	@pTBDEX_TMP_TABLE_SCHEMA			SYSNAME,
	@pTBDEX_TMP_TABLE_NAME				SYSNAME,
	@pTBDEX_TMP_TABLE_SCHEMA_AND_NAME	NVARCHAR(150),
	@pTBDEX_TMP_TABLE_COLUMNS			NVARCHAR(MAX),
	@pTBDEX_TMP_TABLE_DROP_QUERY		NVARCHAR(MAX),
	@pTBDEX_TMP_TABLE_CREATE_QUERY		NVARCHAR(MAX),
	@pTBDEX_TMP_TABLE_INSERT_QUERY		NVARCHAR(MAX)
)
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(128)	= ISNULL(@pBATCH_CREATOR,OBJECT_NAME(@@PROCID)),
			@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,
			@MAIN_QUERY							NVARCHAR(MAX)	= @pMAIN_QUERY,
			@MAIN_QUERY_VAR1					NVARCHAR(50)	= @pMAIN_QUERY_VAR1,
			@MAIN_QUERY_VAR2					NVARCHAR(50)	= @pMAIN_QUERY_VAR2,
			@MAIN_QUERY_VAR3					NVARCHAR(50)	= @pMAIN_QUERY_VAR3,
			@MAIN_QUERY_VAR4					NVARCHAR(50)	= @pMAIN_QUERY_VAR4,
			@MAIN_QUERY_VAR5					NVARCHAR(50)	= @pMAIN_QUERY_VAR5,
			@END_QUERY							NVARCHAR(MAX)	= @pEND_QUERY,
			@END_QUERY_VAR1						NVARCHAR(50)	= @pEND_QUERY_VAR1,
			@END_QUERY_VAR2						NVARCHAR(50)	= @pEND_QUERY_VAR2,
			@END_QUERY_VAR3						NVARCHAR(50)	= @pEND_QUERY_VAR3,
			@END_QUERY_VAR4						NVARCHAR(50)	= @pEND_QUERY_VAR4,
			@END_QUERY_VAR5						NVARCHAR(50)	= @pEND_QUERY_VAR5,
			@FORCE								BIT				= @pFORCE,
			@PROFILE_NAME						NVARCHAR(50)	= @pPROFILE_NAME,
			@MANDANTOR							NVARCHAR(50)	= @pMANDANTOR,
			@EXPORT_TYPE						NVARCHAR(10)	= @pEXPORT_TYPE,
			@DEFAULT_DATA_SEPARATOR				NVARCHAR(50)	= @pDEFAULT_DATA_SEPARATOR,
			@TBDEX_TMP_TABLE_SCHEMA				SYSNAME			= @pTBDEX_TMP_TABLE_SCHEMA,
			@TBDEX_TMP_TABLE_NAME				SYSNAME			= @pTBDEX_TMP_TABLE_NAME,
			@TBDEX_TMP_TABLE_SCHEMA_AND_NAME	NVARCHAR(150)	= @pTBDEX_TMP_TABLE_SCHEMA_AND_NAME,
			@TBDEX_TMP_TABLE_COLUMNS			NVARCHAR(MAX)	= @pTBDEX_TMP_TABLE_COLUMNS,
			@TBDEX_TMP_TABLE_DROP_QUERY			NVARCHAR(MAX)	= @pTBDEX_TMP_TABLE_DROP_QUERY,
			@TBDEX_TMP_TABLE_CREATE_QUERY		NVARCHAR(MAX)	= @pTBDEX_TMP_TABLE_CREATE_QUERY,
			@TBDEX_TMP_TABLE_INSERT_QUERY		NVARCHAR(MAX)	= @pTBDEX_TMP_TABLE_INSERT_QUERY;


	-- 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_COUNT2							SMALLINT		= 0,
			@GUID								BIGINT			= 0,
			@SEQUENCE							TINYINT			= 0,
			@MAINPROCESSING_NAME				NVARCHAR(50)	= NULL,
			@MAINPROCESSING_TYPE				NVARCHAR(10)	= NULL,
			@MAINPROCESSING_QUERY				NVARCHAR(MAX)	= NULL,
			@ERROR_ACTION						NVARCHAR(25)	= NULL,
			@REFERENCE1							NVARCHAR(150)	= NULL,
			@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,
			@TBDEX_TMP_TABLE_CONTENT			NVARCHAR(MAX)	= NULL,
			@EXPORT_NUMBER_SCHEMA				NVARCHAR(25)	= NULL,
			@EXPORT_NUMBER_COUNTER				BIGINT			= NULL,
			@EXPORT_NUMBER						NVARCHAR(25)	= NULL,
			@PLACEHOLDER_NAME					NVARCHAR(50)	= NULL,
			@PLACEHOLDER						NVARCHAR(MAX)	= NULL,
			@PLACEHOLDER_TYPE					NVARCHAR(10)	= 'CONST',
			@HAS_UNRESOLVED_PLACEHOLDER			BIT				= 0,
			@HAS_RESTRICTED_SQL					BIT				= 0,
			@HAS_UNSAFE_TEMP_TARGET				BIT				= 0,
			@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 - @MAIN_QUERY:                      ' + CONVERT(NVARCHAR(50),ISNULL(@MAIN_QUERY,'<NO-VALUE>'));
	PRINT 'PARAMETER15 - @MAIN_QUERY_VAR1:                 ' + CONVERT(NVARCHAR(50),ISNULL(@MAIN_QUERY_VAR1,'<NO-VALUE>'));
	PRINT 'PARAMETER16 - @MAIN_QUERY_VAR2:                 ' + CONVERT(NVARCHAR(50),ISNULL(@MAIN_QUERY_VAR2,'<NO-VALUE>'));
	PRINT 'PARAMETER17 - @MAIN_QUERY_VAR3:                 ' + CONVERT(NVARCHAR(50),ISNULL(@MAIN_QUERY_VAR3,'<NO-VALUE>'));
	PRINT 'PARAMETER18 - @MAIN_QUERY_VAR4:                 ' + CONVERT(NVARCHAR(50),ISNULL(@MAIN_QUERY_VAR4,'<NO-VALUE>'));
	PRINT 'PARAMETER19 - @MAIN_QUERY_VAR5:                 ' + CONVERT(NVARCHAR(50),ISNULL(@MAIN_QUERY_VAR5,'<NO-VALUE>'));
	PRINT 'PARAMETER20 - @END_QUERY:                       ' + CONVERT(NVARCHAR(50),ISNULL(@END_QUERY,'<NO-VALUE>'));
	PRINT 'PARAMETER21 - @END_QUERY_VAR1:                  ' + CONVERT(NVARCHAR(50),ISNULL(@END_QUERY_VAR1,'<NO-VALUE>'));
	PRINT 'PARAMETER22 - @END_QUERY_VAR2:                  ' + CONVERT(NVARCHAR(50),ISNULL(@END_QUERY_VAR2,'<NO-VALUE>'));
	PRINT 'PARAMETER23 - @END_QUERY_VAR3:                  ' + CONVERT(NVARCHAR(50),ISNULL(@END_QUERY_VAR3,'<NO-VALUE>'));
	PRINT 'PARAMETER24 - @END_QUERY_VAR4:                  ' + CONVERT(NVARCHAR(50),ISNULL(@END_QUERY_VAR4,'<NO-VALUE>'));
	PRINT 'PARAMETER25 - @END_QUERY_VAR5:                  ' + CONVERT(NVARCHAR(50),ISNULL(@END_QUERY_VAR5,'<NO-VALUE>'));
	PRINT 'PARAMETER26 - @FORCE:                           ' + CONVERT(NVARCHAR(50),ISNULL(@FORCE,'<NO-VALUE>'));
	PRINT 'PARAMETER27 - @PROFILE_NAME:                    ' + CONVERT(NVARCHAR(50),ISNULL(@PROFILE_NAME,'<NO-VALUE>'));
	PRINT 'PARAMETER28 - @MANDANTOR:                       ' + CONVERT(NVARCHAR(50),ISNULL(@MANDANTOR,'<NO-VALUE>'));
	PRINT 'PARAMETER29 - @EXPORT_TYPE:                     ' + CONVERT(NVARCHAR(50),ISNULL(@EXPORT_TYPE,'<NO-VALUE>'));
	PRINT 'PARAMETER30 - @DEFAULT_DATA_SEPARATOR:          ' + CONVERT(NVARCHAR(50),ISNULL(@DEFAULT_DATA_SEPARATOR,'<NO-VALUE>'));
	PRINT 'PARAMETER31 - @TBDEX_TMP_TABLE_SCHEMA:          ' + CONVERT(NVARCHAR(50),ISNULL(@TBDEX_TMP_TABLE_SCHEMA,'<NO-VALUE>'));
	PRINT 'PARAMETER32 - @TBDEX_TMP_TABLE_NAME:            ' + CONVERT(NVARCHAR(50),ISNULL(@TBDEX_TMP_TABLE_NAME,'<NO-VALUE>'));
	PRINT 'PARAMETER33 - @TBDEX_TMP_TABLE_SCHEMA_AND_NAME: ' + CONVERT(NVARCHAR(50),ISNULL(@TBDEX_TMP_TABLE_SCHEMA_AND_NAME,'<NO-VALUE>'));
	PRINT 'PARAMETER34 - @TBDEX_TMP_TABLE_COLUMNS:         ' + CONVERT(NVARCHAR(50),ISNULL(@TBDEX_TMP_TABLE_COLUMNS,'<NO-VALUE>'));
	PRINT 'PARAMETER35 - @TBDEX_TMP_TABLE_DROP_QUERY:      ' + CONVERT(NVARCHAR(50),ISNULL(@TBDEX_TMP_TABLE_DROP_QUERY,'<NO-VALUE>'));
	PRINT 'PARAMETER36 - @TBDEX_TMP_TABLE_CREATE_QUERY:    ' + CONVERT(NVARCHAR(50),ISNULL(@TBDEX_TMP_TABLE_CREATE_QUERY,'<NO-VALUE>'));
	PRINT 'PARAMETER37 - @TBDEX_TMP_TABLE_INSERT_QUERY:    ' + CONVERT(NVARCHAR(50),ISNULL(@TBDEX_TMP_TABLE_INSERT_QUERY,'<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;
	-----------------------------------------------------------------------------------------------------------------------------------


	--================================================-- Check for export columns --=================================================--
	SET @ROW_COUNT1 = (SELECT count(*) 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,'_','-')));
	IF (@ROW_COUNT1 = 0) BEGIN

		--====================================================-- exception / error --====================================================--
		SET @RETURN_STATUS		= 50022;
		SET @RETURN_STATUS_TEXT = concat('','');
		SET @RETURN_ERROR_TEXT	= concat('Found no valid column configuration in [TBDEX_CFG_OUT_STRUCTURE]!','');
		
		THROW @RETURN_STATUS,@RETURN_ERROR_TEXT,1;
		-----------------------------------------------------------------------------------------------------------------------------------

	END; ELSE BEGIN

		--======================================================-- Output result --======================================================--
		SET @RETURN_STATUS		= 0;
		SET @RETURN_STATUS_TEXT = concat('Found a valid column configuration in [TBDEX_CFG_OUT_STRUCTURE]!','');
		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;
	-----------------------------------------------------------------------------------------------------------------------------------


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

	EXEC [PRDEX_TEST_DYNAMIC_SQL]	@pQUERY			= @TBDEX_TMP_TABLE_CREATE_QUERY,
										@pRETURN_STATUS = 50057,
										@pQUERY_NAME	= N'@TBDEX_TMP_TABLE_CREATE_QUERY';

	SET @HAS_UNSAFE_TEMP_TARGET = CASE WHEN
		(PATINDEX('%DROP TABLE%',UPPER(@TBDEX_TMP_TABLE_DROP_QUERY)) = 0) OR
		(PATINDEX('%CREATE TABLE%',UPPER(@TBDEX_TMP_TABLE_CREATE_QUERY)) = 0) OR
		(
			(PATINDEX('%TEMPDB..%',UPPER(@TBDEX_TMP_TABLE_DROP_QUERY)) = 0)
			AND (PATINDEX('%#%',@TBDEX_TMP_TABLE_DROP_QUERY) = 0)
		) OR
		(
			(PATINDEX('%TEMPDB..%',UPPER(@TBDEX_TMP_TABLE_CREATE_QUERY)) = 0)
			AND (PATINDEX('%#%',@TBDEX_TMP_TABLE_CREATE_QUERY) = 0)
		)
	THEN 1 ELSE 0 END;

	IF (@HAS_UNSAFE_TEMP_TARGET = 1) BEGIN

		SET @RETURN_STATUS		= 50057;
		SET @RETURN_STATUS_TEXT = concat('Blocked unsafe temp table query content in [PRDEX_RUN_MAINPROCESSING]!','');
		SET @RETURN_ERROR_TEXT	= concat('Detected unresolved placeholders, restricted statements, or non-tempdb/non-# table target in drop/create query.','');

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

	--============================================-- Drop dynamic temp table, if exists --===========================================--
	PRINT concat('INFO: ','Executing drop cmd:',char(13),@TBDEX_TMP_TABLE_DROP_QUERY);
	EXEC sp_executesql @TBDEX_TMP_TABLE_DROP_QUERY;
	-----------------------------------------------------------------------------------------------------------------------------------

	--================================================-- create dynamic temp table --================================================--
	PRINT concat('INFO: ','Executing create cmd:',char(13),@TBDEX_TMP_TABLE_CREATE_QUERY);
	EXEC sp_executesql @TBDEX_TMP_TABLE_CREATE_QUERY; -- The structure is based on the config of the table "[TBDEX_CFG_OUT_STRUCTURE]"
	-----------------------------------------------------------------------------------------------------------------------------------

	--===============================================-- Check if table was created --================================================--
	IF (OBJECT_ID(concat('tempdb..',@TBDEX_TMP_TABLE_SCHEMA_AND_NAME), 'U') IS NULL) BEGIN

		--====================================================-- exception / error --====================================================--
		SET @RETURN_STATUS		= 50006;
		SET @RETURN_STATUS_TEXT = concat('','')
		SET @RETURN_ERROR_TEXT	= concat('Cannot create the temp table: ',@TBDEX_TMP_TABLE_SCHEMA_AND_NAME,'!');

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

	END; ELSE BEGIN

		--======================================================-- Output result --======================================================--
		SET @RETURN_STATUS		= 0;
		SET @RETURN_STATUS_TEXT = concat('The temp table: ',@TBDEX_TMP_TABLE_SCHEMA_AND_NAME,' has been created!');
		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;
	-----------------------------------------------------------------------------------------------------------------------------------


	--=============================================-- Check if ref table has content --==============================================--
	SET @ROW_COUNT2 = (SELECT COUNT(*) FROM	[TBDEX_TMP_PROCESS_REFERENCES] WITH (SNAPSHOT)
					   WHERE	[PROFILE_ID]	=   @PROFILE_ID 
					   AND		[BATCH_ID]		=   @BATCH_ID
					   AND		[ADDED_WHO]		IN (@BATCH_CREATOR,@MY_PROCEDURE_NAME));

	IF (@ROW_COUNT2 = 0) BEGIN

		--====================================================-- exception / error --====================================================--
		SET @RETURN_STATUS		= 50010;
		SET @RETURN_STATUS_TEXT = concat('','');
		SET @RETURN_ERROR_TEXT	= concat('Found no fitting lines [TBDEX_TMP_PROCESS_REFERENCES]!','');
		
		THROW @RETURN_STATUS,@RETURN_ERROR_TEXT,1;
		-----------------------------------------------------------------------------------------------------------------------------------

	END; ELSE BEGIN

		--======================================================-- Output result --======================================================--
		SET @RETURN_STATUS		= 0;
		SET @RETURN_STATUS_TEXT = concat('Found ',@ROW_COUNT2,' fitting lines in [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;
		-----------------------------------------------------------------------------------------------------------------------------------

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


	--===========================================-- Get referencies from input table --==============================================--
	DECLARE CURSOR_MAINPROCESSING CURSOR
	LOCAL FAST_FORWARD FOR 
		SELECT  [REFERENCE1]			as 'REFERENCE1',
				[REFERENCE2]			as 'REFERENCE2',
				[REFERENCE3]			as 'REFERENCE3',
				[REFERENCE4]			as 'REFERENCE4',
				[REFERENCE5]			as 'REFERENCE5',
				[EXTERNAL_REFERENCE1]	as 'EXTERNAL_REFERENCE1',
				[EXTERNAL_REFERENCE2]	as 'EXTERNAL_REFERENCE2',
				[EXTERNAL_REFERENCE3]	as 'EXTERNAL_REFERENCE3',
				[EXTERNAL_REFERENCE4]	as 'EXTERNAL_REFERENCE4',
				[EXTERNAL_REFERENCE5]	as 'EXTERNAL_REFERENCE5',
				[EXPORT_NUMBER_COUNTER] as 'EXPORT_NUMBER_COUNTER',
				[EXPORT_NUMBER]         as 'EXPORT_NUMBER'
		FROM	[TBDEX_TMP_PROCESS_REFERENCES] WITH (SNAPSHOT)
		WHERE	[PROFILE_ID]	=   @PROFILE_ID 
		AND		[BATCH_ID]		=   @BATCH_ID
		AND		[ADDED_WHO]		IN (@BATCH_CREATOR,@MY_PROCEDURE_NAME);

	OPEN CURSOR_MAINPROCESSING 
	FETCH NEXT FROM CURSOR_MAINPROCESSING INTO @REFERENCE1,@REFERENCE2,@REFERENCE3,@REFERENCE4,@REFERENCE5,@EXTERNAL_REFERENCE1,@EXTERNAL_REFERENCE2,@EXTERNAL_REFERENCE3,@EXTERNAL_REFERENCE4,@EXTERNAL_REFERENCE5,@EXPORT_NUMBER_COUNTER,@EXPORT_NUMBER;
	WHILE @@FETCH_STATUS = 0
		BEGIN
	
			--=================================================-- Call input procedure  --==================================================--
			EXEC @RETURN_STATUS = [PRDEX_SET_QUERY]	@pPROFILE_ID				= @PROFILE_ID,
													@pTEST_MODE					= @TEST_MODE,
													@pASYNC_MODE				= @ASYNC_MODE,
													@pBATCH_ID					= @BATCH_ID,
													@pBATCH_CREATOR				= @BATCH_CREATOR,
													@pLANGUAGE					= @LANGUAGE,
													@pLOG_LEVEL					= @LOG_LEVEL,
													@pSTART_QUERY				= @START_QUERY,
													@pSTART_QUERY_VAR1			= @START_QUERY_VAR1,
													@pSTART_QUERY_VAR2			= @START_QUERY_VAR2,
													@pSTART_QUERY_VAR3			= @START_QUERY_VAR3,
													@pSTART_QUERY_VAR4			= @START_QUERY_VAR4,
													@pSTART_QUERY_VAR5			= @START_QUERY_VAR5,
													@pMAIN_QUERY				= @MAIN_QUERY,
													@pMAIN_QUERY_VAR1			= @MAIN_QUERY_VAR1,
													@pMAIN_QUERY_VAR2			= @MAIN_QUERY_VAR2,
													@pMAIN_QUERY_VAR3			= @MAIN_QUERY_VAR3,
													@pMAIN_QUERY_VAR4			= @MAIN_QUERY_VAR4,
													@pMAIN_QUERY_VAR5			= @MAIN_QUERY_VAR5,
													@pEND_QUERY					= @END_QUERY,
													@pEND_QUERY_VAR1			= @END_QUERY_VAR1,
													@pEND_QUERY_VAR2			= @END_QUERY_VAR2,
													@pEND_QUERY_VAR3			= @END_QUERY_VAR3,
													@pEND_QUERY_VAR4			= @END_QUERY_VAR4,
													@pEND_QUERY_VAR5			= @END_QUERY_VAR5,
													@pFORCE						= @FORCE,
													@pPROFILE_NAME				= @PROFILE_NAME,
													@pMANDANTOR					= @MANDANTOR,
													@pEXPORT_TYPE				= @EXPORT_TYPE,
													@pEXPORT_NUMBER_SCHEMA		= @EXPORT_NUMBER_SCHEMA,
													@pDEFAULT_DATA_SEPARATOR	= @DEFAULT_DATA_SEPARATOR,
													@pREFERENCE1				= @REFERENCE1,
													@pREFERENCE2				= @REFERENCE2,
													@pREFERENCE3				= @REFERENCE3,
													@pREFERENCE4				= @REFERENCE4,
													@pREFERENCE5				= @REFERENCE5,
													@pEXTERNAL_REFERENCE1		= @EXTERNAL_REFERENCE1,
													@pEXTERNAL_REFERENCE2		= @EXTERNAL_REFERENCE2,
													@pEXTERNAL_REFERENCE3		= @EXTERNAL_REFERENCE3,
													@pEXTERNAL_REFERENCE4		= @EXTERNAL_REFERENCE4,
													@pEXTERNAL_REFERENCE5		= @EXTERNAL_REFERENCE5;

			IF (@RETURN_STATUS <> 0) BEGIN

				--====================================================-- exception / error --====================================================--
				SET @RETURN_STATUS		= @RETURN_STATUS;
				SET @RETURN_STATUS_TEXT = concat('Error occurred in [PRDEX_SET_QUERY]!','');
				SET @RETURN_ERROR_TEXT	= concat('Check previous error text!','');
		
				THROW @RETURN_STATUS,@RETURN_ERROR_TEXT,1;
				-----------------------------------------------------------------------------------------------------------------------------------

			END; ELSE BEGIN

				--======================================================-- Output result --======================================================--
				SET @RETURN_STATUS		= 0;
				SET @RETURN_STATUS_TEXT = concat('Procedure [PRDEX_SET_QUERY] worked just fine!','');
				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;
			-----------------------------------------------------------------------------------------------------------------------------------


			--=============================================-- Call input content procedure  --==============================================--
			EXEC @RETURN_STATUS = [PRDEX_GET_INPUT_CONTENT]	@pPROFILE_ID						= @PROFILE_ID,
															@pTEST_MODE							= @TEST_MODE,
															@pASYNC_MODE						= @ASYNC_MODE,
															@pBATCH_ID							= @BATCH_ID,
															@pBATCH_CREATOR						= @BATCH_CREATOR,
															@pLANGUAGE							= @LANGUAGE,
															@pLOG_LEVEL							= @LOG_LEVEL,
															@pSTART_QUERY						= @START_QUERY,
															@pSTART_QUERY_VAR1					= @START_QUERY_VAR1,
															@pSTART_QUERY_VAR2					= @START_QUERY_VAR2,
															@pSTART_QUERY_VAR3					= @START_QUERY_VAR3,
															@pSTART_QUERY_VAR4					= @START_QUERY_VAR4,
															@pSTART_QUERY_VAR5					= @START_QUERY_VAR5,
															@pMAIN_QUERY						= @MAIN_QUERY,
															@pMAIN_QUERY_VAR1					= @MAIN_QUERY_VAR1,
															@pMAIN_QUERY_VAR2					= @MAIN_QUERY_VAR2,
															@pMAIN_QUERY_VAR3					= @MAIN_QUERY_VAR3,
															@pMAIN_QUERY_VAR4					= @MAIN_QUERY_VAR4,
															@pMAIN_QUERY_VAR5					= @MAIN_QUERY_VAR5,
															@pEND_QUERY							= @END_QUERY,
															@pEND_QUERY_VAR1					= @END_QUERY_VAR1,
															@pEND_QUERY_VAR2					= @END_QUERY_VAR2,
															@pEND_QUERY_VAR3					= @END_QUERY_VAR3,
															@pEND_QUERY_VAR4					= @END_QUERY_VAR4,
															@pEND_QUERY_VAR5					= @END_QUERY_VAR5,
															@pFORCE								= @FORCE,
															@pPROFILE_NAME						= @PROFILE_NAME,
															@pMANDANTOR							= @MANDANTOR,
															@pEXPORT_TYPE						= @EXPORT_TYPE,
															@pEXPORT_NUMBER_SCHEMA				= @EXPORT_NUMBER_SCHEMA,
															@pDEFAULT_DATA_SEPARATOR			= @DEFAULT_DATA_SEPARATOR,
															@pTBDEX_TMP_TABLE_SCHEMA			= @TBDEX_TMP_TABLE_SCHEMA,
															@pTBDEX_TMP_TABLE_NAME				= @TBDEX_TMP_TABLE_NAME,
															@pTBDEX_TMP_TABLE_SCHEMA_AND_NAME	= @TBDEX_TMP_TABLE_SCHEMA_AND_NAME,
															@pTBDEX_TMP_TABLE_COLUMNS			= @TBDEX_TMP_TABLE_COLUMNS,
															@pTBDEX_TMP_TABLE_DROP_QUERY		= @TBDEX_TMP_TABLE_DROP_QUERY,
															@pTBDEX_TMP_TABLE_CREATE_QUERY		= @TBDEX_TMP_TABLE_CREATE_QUERY,
															@pTBDEX_TMP_TABLE_INSERT_QUERY		= @TBDEX_TMP_TABLE_INSERT_QUERY,
															@pREFERENCE1						= @REFERENCE1,
															@pREFERENCE2						= @REFERENCE2,
															@pREFERENCE3						= @REFERENCE3,
															@pREFERENCE4						= @REFERENCE4,
															@pREFERENCE5						= @REFERENCE5,
															@pEXTERNAL_REFERENCE1				= @EXTERNAL_REFERENCE1,
															@pEXTERNAL_REFERENCE2				= @EXTERNAL_REFERENCE2,
															@pEXTERNAL_REFERENCE3				= @EXTERNAL_REFERENCE3,
															@pEXTERNAL_REFERENCE4				= @EXTERNAL_REFERENCE4,
															@pEXTERNAL_REFERENCE5				= @EXTERNAL_REFERENCE5;

			IF (@RETURN_STATUS <> 0) BEGIN

				--====================================================-- exception / error --====================================================--
				SET @RETURN_STATUS		= @RETURN_STATUS;
				SET @RETURN_STATUS_TEXT = concat('Error occurred in [PRDEX_GET_INPUT_CONTENT]!','');
				SET @RETURN_ERROR_TEXT	= concat('Check previous error text!','');
		
				THROW @RETURN_STATUS,@RETURN_ERROR_TEXT,1;
				-----------------------------------------------------------------------------------------------------------------------------------

			END; ELSE BEGIN

				--======================================================-- Output result --======================================================--
				SET @RETURN_STATUS		= 0;
				SET @RETURN_STATUS_TEXT = concat('Procedure [PRDEX_GET_INPUT_CONTENT] worked just fine!','');
				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;
			-----------------------------------------------------------------------------------------------------------------------------------

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


	--======================================================-- 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 '';
	PRINT @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 'ERROR: ' + @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('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