iSeries: Create a GUID (SQL)

Date: 2016-03-19

-- Create a new random GUID (as Function)
CREATE FUNCTION UUID()
RETURNS CHAR(36)
LANGUAGE SQL
CONTAINS SQL
NO EXTERNAL ACTION
DETERMINISTIC
RETURN LOWER( 
	RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 8) || '-' || 
	RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 4) || '-' ||
	RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 4) || '-' ||	
	RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 4) || '-' ||	
	RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 8) || RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 4)
);


INSERT INTO TABLE_GUIDS (Oid, Guid) VALUES (UUID(), UUID());

-- Or inline
BEGIN ATOMIC
	DECLARE @GUID CHAR(36) NOT NULL DEFAULT '';
	SET @GUID=LOWER( 
		RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 8) || '-' ||
		RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 4) || '-' ||
		RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 4) || '-' ||
		RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 4) || '-' ||
		RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 8) || RIGHT(LPAD(HEX(INT(RAND() * 1000000000)), 8, '0'), 4)
		);

			
	INSERT INTO TABLE_GUIDS (Oid, Guid) VALUES (@GUID, @GUID); 
END

1330cookie-checkiSeries: Create a GUID (SQL)