Skip to content

Instantly share code, notes, and snippets.

@emptyother
Forked from tzal/uuid_from_bin.sql
Created August 21, 2020 09:21
Show Gist options
  • Save emptyother/7401889316fa2741ff76de8cbf4872f3 to your computer and use it in GitHub Desktop.
Save emptyother/7401889316fa2741ff76de8cbf4872f3 to your computer and use it in GitHub Desktop.
MySQL: convert BINARY(16) to GUID (UUID)
# MySQL: convert BINARY(16) to GUID (Microsoft-style UUID)
# 0x11223344556677889900AABBCCDDEEFF → '44332211-6655-8877-9900-AABBCCDDEEFF'
# usage: CREATE TABLE example(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, guid BINARY(16) NOT NULL UNIQUE);
# SELECT id, uuid_from_bin(guid) FROM example;
CREATE FUNCTION uuid_from_bin(b BINARY(16))
RETURNS char(36) CHARSET utf8
DETERMINISTIC
BEGIN
DECLARE h CHAR(32);
SET h=HEX(b);
RETURN CONCAT(SUBSTRING(h,7,2), SUBSTRING(h,5,2), SUBSTRING(h,3,2), SUBSTRING(h,1,2),
'-', SUBSTRING(h,11,2), SUBSTRING(h,9,2),
'-', SUBSTRING(h,15,2), SUBSTRING(h,13,2),
'-', SUBSTRING(h,17,4),
'-', SUBSTRING(h,21,12));
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment