SET PATH *LIBL ; 

CREATE OR REPLACE FUNCTION SAILPOINT.ES_GET_EMPLOYEE_NUMBER ( 
	USERNAME CHAR(10) ) 
	RETURNS CLOB(2147483647)   
	LANGUAGE SQL 
	SPECIFIC SAILPOINT.ESMEMPNO 
	NOT DETERMINISTIC 
	MODIFIES SQL DATA 
	CALLED ON NULL INPUT 
	NOT FENCED 
	SET OPTION  ALWBLK = *ALLREAD , 
	ALWCPYDTA = *OPTIMIZE , 
	COMMIT = *NONE , 
	DECRESULT = (31, 31, 00) , 
	DYNDFTCOL = *NO , 
	DYNUSRPRF = *USER , 
	SRTSEQ = *HEX   
	BEGIN 
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION 
BEGIN 
DECLARE V_SQLSTATE CHAR ( 5 ) ; 
DECLARE V_DB2_RETURN_CODE INT ; 
DECLARE V_DB2_MESSAGE_ID CHAR ( 7 ) ; 
DECLARE V_ERROR_MESSAGE CLOB ( 2048 ) ; 
-- Capture diagnostic info 
GET DIAGNOSTICS CONDITION 1 
V_DB2_RETURN_CODE = DB2_RETURNED_SQLCODE , 
V_SQLSTATE = RETURNED_SQLSTATE , 
V_ERROR_MESSAGE = MESSAGE_TEXT , 
V_DB2_MESSAGE_ID = DB2_MESSAGE_ID ; 
RETURN 
( 
VALUES JSON_OBJECT ( 
'success' VALUE 'false' , 'SQLInfo' VALUE JSON_OBJECT ( 
'SQLState' VALUE V_SQLSTATE , 
'SQLCode' VALUE V_DB2_RETURN_CODE , 
'messageID' VALUE V_DB2_MESSAGE_ID , 
'message' VALUE V_ERROR_MESSAGE , 
'currentTimestamp' VALUE CURRENT_TIMESTAMP 
) 
) ) ; 
END ; 
DECLARE GLOBAL TEMPORARY TABLE SESSION . EMPNO_LIST ( 
ENVID CHAR ( 2 ) , LIB CHAR ( 10 ) , EXUSER CHAR ( 10 ) , EMPNO CHAR ( 8 ) ) 
WITH REPLACE ; 
FOR SELECT DISTINCT A . ENVID , TRIM ( 'CESLIB' || 
CASE A . ENVID 
WHEN 'MM' THEN '' 
ELSE RIGHT ( A . ENVID , 1 ) 
END ) AS CESLIB 
FROM TABLE ( 
SELECT ROW_NUMBER ( ) OVER ( 
) AS RN , ENVID 
FROM JSON_TABLE ( 
SAILPOINT . ES_GET_ALL_MAPICS_ENVIRONMENTS ( ) , 
'$.data[*]' 
COLUMNS ( 
ENVID VARCHAR ( 2 ) CCSID 37 PATH '$.envId' 
) 
) 
) A 
DO 
BEGIN 
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION 
BEGIN 
END ; 
SET CISTOOLS . SQL_STATEMENT = 
'INSERT INTO SESSION.EMPNO_LIST ' || 'Select ''' || 
ENVID || ''', ''' || CESLIB || ''', ExUser, Ext08A ' 
|| 'FROM ' || CESLIB || '.ESUEXP WHERE ExUser = ''' 
|| TRIM ( USERNAME ) || '''' ; 
EXECUTE IMMEDIATE CISTOOLS . SQL_STATEMENT ; 
END ; 
END FOR ; 
RETURN 
COALESCE ( 
JSON_OBJECT ( 
'success' : 'true' , 'data' VALUE ( 
SELECT JSON_ARRAYAGG ( 
JSON_OBJECT ( 
'envId' VALUE ENVID , 'userEmpno' VALUE TRIM ( 
EMPNO ) 
) FORMAT JSON 
) 
FROM SESSION . EMPNO_LIST ) FORMAT JSON ABSENT ON NULL 
) , JSON_OBJECT ( 
'success' VALUE 'false' , 'SQLInfo' VALUE JSON_OBJECT ( 
'messageID' VALUE 'SQL02000' , 
'message' VALUE 'Requested resouce not found ' , 
'currentTimestamp' VALUE CURRENT_TIMESTAMP 
) 
) ) ; 
END  ; 

GRANT ALTER , EXECUTE   
ON SPECIFIC FUNCTION SAILPOINT.ESMEMPNO 
TO AMAPICS WITH GRANT OPTION ; 

GRANT EXECUTE   
ON SPECIFIC FUNCTION SAILPOINT.ESMEMPNO 
TO PUBLIC ; 

