SET PATH *LIBL ; 

CREATE OR REPLACE FUNCTION CISTOOLS.SPLIT_COLUMNS ( 
	SQLSTMT VARCHAR(32000) ) 
	RETURNS TABLE ( 
	COLUMN_POSITION INTEGER , 
	COLUMN_VALUE VARCHAR(512) )   
	LANGUAGE SQL 
	SPECIFIC CISTOOLS.SPLIT_COLUMNS 
	NOT DETERMINISTIC 
	READS SQL DATA 
	CALLED ON NULL INPUT 
	NO EXTERNAL ACTION 
	CONCURRENT ACCESS RESOLUTION DEFAULT 
	SET OPTION  ALWBLK = *ALLREAD , 
	ALWCPYDTA = *OPTIMIZE , 
	COMMIT = *NONE , 
	DBGVIEW = *SOURCE , 
	DECRESULT = (31, 31, 00) , 
	DYNDFTCOL = *NO , 
	DYNUSRPRF = *OWNER , 
	OPTLOB = *YES , 
	SQLCURRULE = *STD , 
	SRTSEQ = *HEX   
	BEGIN 
DECLARE STMTHANDLE BIGINT ; 
DECLARE DESCHANDLE VARCHAR ( 128 ) ; 
DECLARE VORDINALPOS INTEGER DEFAULT 0 ; 
DECLARE OVERLAYSQL VARCHAR ( 32000 ) DEFAULT '' ; 
DECLARE VCOLUMNNAME VARCHAR ( 128 ) DEFAULT ' ' ; 
DECLARE I INTEGER DEFAULT 1 ; 
DECLARE TOKEN VARCHAR ( 128 ) DEFAULT ' ' ; 
DECLARE RTNSQLCODE INT ; 
DECLARE COLCOUNT INTEGER ; 
DECLARE VVALUE VARCHAR ( 512 ) DEFAULT '' ; 
DECLARE SQLCODE INTEGER DEFAULT 0 ; 
DECLARE SQLSTATE CHAR ( 5 ) DEFAULT '00000' ; 
DECLARE STMTCURSOR CURSOR FOR STMTHANDLE ; 
DECLARE CONTINUE HANDLER FOR SQLSTATE '22501' , SQLSTATE '33000' 
BEGIN 
DEALLOCATE DESCRIPTOR LOCAL DESCHANDLE ; 
GET DIAGNOSTICS CONDITION 1 TOKEN = DB2_ORDINAL_TOKEN_2 ; 
SET COLCOUNT = TOKEN ; 
ALLOCATE DESCRIPTOR LOCAL DESCHANDLE WITH MAX COLCOUNT ; 
DESCRIBE STMTHANDLE USING DESCRIPTOR LOCAL DESCHANDLE ; 
SET I = 1 ; 
END ; 
SET DESCHANDLE = 'Descr' || HEX ( GENERATE_UNIQUE ( ) ) ; 
PREPARE STMTHANDLE FROM SQLSTMT ; 
ALLOCATE DESCRIPTOR LOCAL DESCHANDLE WITH MAX 1024 ; 
DESCRIBE STMTHANDLE USING DESCRIPTOR LOCAL DESCHANDLE ; 
GET DESCRIPTOR LOCAL DESCHANDLE COLCOUNT = COUNT ; 
--build dynamic varchar sql statement 
SET OVERLAYSQL = ( 
SELECT 'Select ' || 
CAST ( 
LISTAGG ( 'Cast (C' || RN || ' As Varchar(512) Ccsid 37)' , 
', ' 
) || ' From Table(Select * From Table(' || SQLSTMT || ' ) X(' 
|| LISTAGG ( 'C' || RN , ', ' ) || ')) ' AS CLOB ( 2 G ) ) 
FROM TABLE ( 
CISTOOLS . ROWS_COUNTER ( COLCOUNT ) 
) ) ; 
DEALLOCATE DESCRIPTOR LOCAL DESCHANDLE ; 
PREPARE STMTHANDLE FROM OVERLAYSQL ; 
ALLOCATE DESCRIPTOR LOCAL DESCHANDLE WITH MAX COLCOUNT ; 
DESCRIBE STMTHANDLE USING DESCRIPTOR LOCAL DESCHANDLE ; 
OPEN STMTCURSOR ; 
FETCH STMTCURSOR 
INTO SQL DESCRIPTOR LOCAL DESCHANDLE ; 
WHILE I <= COLCOUNT DO 
GET DESCRIPTOR LOCAL DESCHANDLE VALUE I VVALUE = DATA ; 
PIPE ( I , VVALUE ) ; 
SET I = I + 1 ; 
END WHILE ; 
DEALLOCATE DESCRIPTOR LOCAL DESCHANDLE ; 
CLOSE STMTCURSOR ; 
RETURN ; 
END  ; 

GRANT ALTER , EXECUTE   
ON SPECIFIC FUNCTION CISTOOLS.SPLIT_COLUMNS 
TO AMAPICS WITH GRANT OPTION ; 

GRANT EXECUTE   
ON SPECIFIC FUNCTION CISTOOLS.SPLIT_COLUMNS 
TO PUBLIC ; 

