Skip to content

Instantly share code, notes, and snippets.

@jeffjohnson9046
Last active February 21, 2017 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffjohnson9046/5a9dbf70003bfe61a2391c212e3355a5 to your computer and use it in GitHub Desktop.
Save jeffjohnson9046/5a9dbf70003bfe61a2391c212e3355a5 to your computer and use it in GitHub Desktop.
functions for converting a UUID stored as VARBINARY(16) into its UUID form and vice versa
/*
* From here: http://mysql.rjweb.org/doc.php/uuid
*/
-- Convert a formatted UUID to a BINARY(16)
CREATE FUNCTION UuidToBin(_uuid CHAR(36))
RETURNS BINARY(16)
LANGUAGE SQL DETERMINISTIC CONTAINS SQL SQL SECURITY INVOKER
RETURN
UNHEX(CONCAT(
SUBSTR(_uuid, 15, 4),
SUBSTR(_uuid, 10, 4),
SUBSTR(_uuid, 1, 8),
SUBSTR(_uuid, 20, 4),
SUBSTR(_uuid, 25) ));
-- Convert a VARBINARY(16) to a formatted UUID
CREATE FUNCTION UuidFromBin(_bin BINARY(16))
RETURNS CHAR(36)
LANGUAGE SQL DETERMINISTIC CONTAINS SQL SQL SECURITY INVOKER
RETURN
LCASE(CONCAT_WS('-', HEX(SUBSTR(_bin, 1, 4)),
HEX(SUBSTR(_bin, 5, 2)),
HEX(SUBSTR(_bin, 7, 2)),
HEX(SUBSTR(_bin, 9, 2)),
HEX(SUBSTR(_bin, 11))));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment