SET PATH *LIBL ; 

CREATE OR REPLACE FUNCTION CISTOOLS.GENERATE_SQL ( 
	INOBJ VARCHAR(256) , 
	INLIB VARCHAR(128) DEFAULT  '*ALL'  , 
	INTYP VARCHAR(128) DEFAULT  '*ALL'  ) 
	RETURNS VARCHAR(32000)   
	LANGUAGE SQL 
	SPECIFIC CISTOOLS.GENERATE_SQL 
	NOT DETERMINISTIC 
	MODIFIES SQL DATA 
	CALLED ON NULL INPUT 
	SET OPTION  ALWBLK = *ALLREAD , 
	ALWCPYDTA = *OPTIMIZE , 
	COMMIT = *NONE , 
	DECRESULT = (31, 31, 00) , 
	DYNDFTCOL = *NO , 
	DYNUSRPRF = *OWNER , 
	SRTSEQ = *HEX   
	BEGIN 
DECLARE RS RESULT_SET_LOCATOR VARYING ; 
DECLARE NOT_FOUND VARCHAR ( 256 ) ; 
DECLARE RETURN_VAL VARCHAR ( 32000 ) ; 
DECLARE SPLIT_POS SMALLINT DEFAULT 0 ; 
DECLARE LIB , TYP , OBJ VARCHAR ( 128 ) DEFAULT '' ; 
DECLARE CONTINUE HANDLER FOR SQLSTATE '01532' 
BEGIN 
SET RETURN_VAL = NOT_FOUND ; 
END ; 
SET ( LIB , TYP , OBJ ) = ( UPPER ( INLIB ) , UPPER ( INTYP ) , UPPER ( INOBJ )) ; 
SET SPLIT_POS = REGEXP_INSTR ( OBJ , '[.|/]' ) ; 
IF SPLIT_POS > 0 
AND ( LIB IS NULL 
OR TRIM ( LIB ) = '' 
OR TRIM ( LIB ) = '*ALL' ) THEN 
SET LIB = SUBSTR ( OBJ , 1 , SPLIT_POS - 1 ) ; 
SET OBJ = SUBSTR ( OBJ , SPLIT_POS + 1 ) ; 
END IF ; 
SELECT OBJLONGNAME , OBJLIB , SQL_OBJECT_TYPE 
INTO OBJ , LIB , TYP 
FROM 
TABLE ( 
SELECT * 
FROM TABLE ( 
VALUES ( 
CASE LIB 
WHEN '*ALL' THEN '' 
ELSE LIB 
END ) 
UNION ALL 
SELECT SCHEMA_NAME 
FROM LIBLIST 
UNION ALL 
VALUES ( 
CASE LIB 
WHEN '*ALL' THEN LIB 
ELSE '' 
END ) 
) 
) X ( LIB_NAME ) 
JOIN TABLE ( 
QSYS2 . OBJECT_STATISTICS ( 
LIB_NAME , '*ALL' , NULLIF ( OBJ , '' ) ) 
) 
ON 1 = 1 
WHERE SQL_OBJECT_TYPE IS NOT NULL 
AND LIB_NAME <> '' 
AND SQL_OBJECT_TYPE = COALESCE ( 
NULLIF ( TYP , '*ALL' ) , SQL_OBJECT_TYPE ) 
AND OBJ = COALESCE ( OBJLONGNAME , OBJNAME ) 
LIMIT 1 ; 
CALL QSYS2 . GENERATE_SQL ( DATABASE_OBJECT_NAME => OBJ , 
DATABASE_OBJECT_LIBRARY_NAME => LIB , DATABASE_OBJECT_TYPE => TYP , 
CREATE_OR_REPLACE_OPTION => '1' ) ; 
ASSOCIATE RESULT SET LOCATOR ( RS ) WITH PROCEDURE GENERATE_SQL ; 
ALLOCATE SQL_CUR CURSOR FOR RESULT SET RS ; 
SET CISTOOLS . SQL_STATEMENT = NULL ; 
SET CISTOOLS . SQL_STATEMENT = ( 
SELECT TRIM ( LISTAGG ( CAST ( TRIM ( SRCDTA ) AS VARCHAR ( 32000 ) ) ) ) 
FROM QTEMP . Q_GENSQL 
WHERE TRIM ( SRCDTA ) <> '' 
AND SRCSEQ > 6 ) ; 
IF CISTOOLS . SQL_STATEMENT IS NULL THEN 
SET RETURN_VAL = 'Object Not Found' ; 
END IF ; 
SET RETURN_VAL = CISTOOLS . SQL_STATEMENT ; 
CLOSE SQL_CUR ; 
RETURN RETURN_VAL ; 
END  ; 

COMMENT ON PARAMETER SPECIFIC FUNCTION CISTOOLS.GENERATE_SQL 
( INOBJ IS 'Object Name' , 
	INLIB IS 'Library Name' , 
	INTYP IS 'SQL Object Type' ) ; 

LABEL ON SPECIFIC FUNCTION CISTOOLS.GENERATE_SQL 
	IS 'Generate SQL From Object' ; 

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

GRANT EXECUTE   
ON SPECIFIC FUNCTION CISTOOLS.GENERATE_SQL 
TO PUBLIC ; 

