SET PATH *LIBL ; 

CREATE OR REPLACE PROCEDURE CISTOOLS.JSON_TO_DB2 ( 
	IN JSON_IN CLOB(2147483647) ) 
	DYNAMIC RESULT SETS 1 
	LANGUAGE SQL 
	SPECIFIC CISTOOLS.JSON_TO_DB2 
	NOT DETERMINISTIC 
	MODIFIES SQL DATA 
	CALLED ON NULL INPUT 
	PROGRAM TYPE SUB 
	SET OPTION  ALWBLK = *ALLREAD , 
	ALWCPYDTA = *OPTIMIZE , 
	COMMIT = *NONE , 
	DBGVIEW = *SOURCE , 
	DECRESULT = (31, 31, 00) , 
	DYNDFTCOL = *NO , 
	DYNUSRPRF = *OWNER , 
	SRTSEQ = *HEX   
	BEGIN 
DECLARE FIRST_OBJ CLOB ( 5 M ) ; 
DECLARE COL_LIST CLOB ( 10 M ) DEFAULT '' ; 
DECLARE STMT CLOB ( 2 G ) ; 
DECLARE JSON_KEY VARCHAR ( 128 ) ; 
DECLARE PAD VARCHAR ( 3 ) DEFAULT ' ' ; 
DECLARE POS INT DEFAULT 1 ; 
DECLARE SEQ INT DEFAULT 1 ; 
-- cursor for returning the result 
DECLARE C1 CURSOR WITH RETURN FOR S1 ; 
SET PAD = ' ' ; 
FOR SELECT COL_NAME , COL_VALUE 
FROM TABLE ( 
SELECT JT . KEY AS COL_NAME , JT . VALUE AS COL_VALUE 
FROM TABLE ( 
VALUES JSON_QUERY ( JSON_IN , '$[0]' ) 
) X ( FIRST_OBJ ) , TABLE ( 
VALUES '[' || 
REGEXP_REPLACE ( 
REGEXP_REPLACE ( 
REGEXP_REPLACE ( 
FIRST_OBJ , '"([^"]*)":([^,}]*)' , 
'{"key":"\1","value":\2}' ) , '\}\s*\}' , 
'},' ) , '\{\s*\{' , '{' ) || ']' 
) Y ( PARSED_JSON ) , JSON_TABLE ( 
PARSED_JSON , 
'$[*]' 
COLUMNS ( 
KEY VARCHAR ( 50 ) PATH '$.key' , 
VALUE VARCHAR ( 50 ) PATH '$.value' 
) 
) AS JT 
) 
DO 
-- Decide type 
IF UPPER ( COL_VALUE ) IN ( 'TRUE' , 'FALSE' ) THEN 
SET COL_LIST = COL_LIST || PAD || DELIMIT_NAME ( COL_NAME ) || 
' SMALLINT PATH ''$.' || COL_NAME || '''' ; 
ELSEIF REGEXP_LIKE ( COL_VALUE , '^-?[0-9]+(\.[0-9]+)?$' ) THEN 
IF REGEXP_COUNT ( COL_VALUE , '\.' ) = 1 THEN 
SET COL_LIST = COL_LIST || PAD || DELIMIT_NAME ( COL_NAME ) || 
' Numeric(19,10) PATH ''$.' || COL_NAME || '''' ; 
ELSE 
SET COL_LIST = COL_LIST || PAD || DELIMIT_NAME ( COL_NAME ) || 
' Integer PATH ''$.' || COL_NAME || '''' ; 
END IF ; 
ELSE 
SET COL_LIST = COL_LIST || PAD || 
DELIMIT_NAME ( DELIMIT_NAME ( COL_NAME ) ) || 
' VARCHAR(256) PATH ''$.' || COL_NAME || '''' ; 
END IF ; 
SET PAD = ', ' ; 
END FOR ; 
-- Step 3: build dynamic JSON_TABLE statement 
SET STMT = STRIP_SPACES ( '
        SELECT JT.*
        FROM JSON_TABLE(
?,
''$[*]''
            COLUMNS (
                ' || COL_LIST || '
)
        ) AS jt
    ' ) ; 

SET CISTOOLS . SQL_STATEMENT = STMT ; 
-- Step 4: prepare and return cursor 
PREPARE S1 FROM STMT ; 
OPEN C1 USING JSON_IN ; 
END  ; 

GRANT ALTER , EXECUTE   
ON SPECIFIC PROCEDURE CISTOOLS.JSON_TO_DB2 
TO AMAPICS WITH GRANT OPTION ; 

GRANT EXECUTE   
ON SPECIFIC PROCEDURE CISTOOLS.JSON_TO_DB2 
TO PUBLIC ; 

