SET PATH "QSYS","QSYS2","SYSPROC","SYSIBMADM","QTEMP" ; 

CREATE OR REPLACE FUNCTION CISTOOLS.CYMD2DATE ( 
	CYMD_DATE NUMERIC(7, 0) DEFAULT  0  ) 
	RETURNS DATE   
	LANGUAGE SQL 
	SPECIFIC CISTOOLS.CYMD2DATE 
	NOT DETERMINISTIC 
	MODIFIES SQL DATA 
	CALLED ON NULL INPUT 
	SET OPTION  ALWBLK = *ALLREAD , 
	ALWCPYDTA = *OPTIMIZE , 
	COMMIT = *NONE , 
	DBGVIEW = *SOURCE , 
	DECRESULT = (31, 31, 00) , 
	DFTRDBCOL = QTEMP , 
	DYNDFTCOL = *NO , 
	DYNUSRPRF = *USER , 
	SRTSEQ = *HEX   
	BEGIN 
DECLARE CHAR_DATE CHAR ( 8 ) ; 
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION RETURN NULL ; 
SET CHAR_DATE = 
CASE 
WHEN 
LEFT ( LPAD ( CYMD_DATE , 7 , '0' ) , 1 ) = '0' 
THEN '19' || RIGHT ( LPAD ( CYMD_DATE , 7 , '0' ) , 6 ) 
WHEN 
LEFT ( LPAD ( CYMD_DATE , 7 , '0' ) , 2 ) >= '1' 
THEN 
( INT ( LEFT ( LPAD ( CYMD_DATE , 7 , '0' ) , 1 ) ) + 19 ) || 
RIGHT ( LPAD ( CYMD_DATE , 7 , '0' ) , 6 ) 
END ; 
-- TO_DATE will validate the date and throw exception if invalid 
-- Exception handler will catch and return NULL 
RETURN TO_DATE ( CHAR_DATE , 'YYYYMMDD' ) ; 
END  ; 

COMMENT ON PARAMETER SPECIFIC FUNCTION CISTOOLS.CYMD2DATE 
( CYMD_DATE IS 'CYMD Date Format' ) ; 

LABEL ON SPECIFIC FUNCTION CISTOOLS.CYMD2DATE 
	IS 'Cymd To Date' ; 

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

GRANT EXECUTE   
ON SPECIFIC FUNCTION CISTOOLS.CYMD2DATE 
TO PUBLIC ; 

