-
-
Save emptyother/7401889316fa2741ff76de8cbf4872f3 to your computer and use it in GitHub Desktop.
MySQL: convert BINARY(16) to GUID (UUID)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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