漫漫长路,其修远兮!
分类: Mysql/postgreSQL
2013-02-20 10:54:02
通常用UUID做唯一标识,需要在数据库中进行存储。
UUID的格式
数据库中直接存储UUID的坏处:
DELIMITER $$ CREATE FUNCTION `GuidToBinary`( $Data VARCHAR(36) ) RETURNS binary(16) BEGIN DECLARE $Result BINARY(16) DEFAULT NULL; IF $Data IS NOT NULL THEN SET $Data = REPLACE($Data,'-',''); SET $Result = CONCAT(UNHEX(SUBSTRING($Data,7,2)),UNHEX(SUBSTRING($Data,5,2)),UNHEX(SUBSTRING($Data,3,2)), UNHEX(SUBSTRING($Data,1,2)), UNHEX(SUBSTRING($Data,11,2)),UNHEX(SUBSTRING($Data,9,2)),UNHEX(SUBSTRING($Data,15,2)) , UNHEX(SUBSTRING($Data,13,2)), UNHEX(SUBSTRING($Data,17,16))); END IF; RETURN $Result; END $$ CREATE FUNCTION `ToGuid`( $Data BINARY(16) ) RETURNS char(36) CHARSET utf8 BEGIN DECLARE $Result CHAR(36) DEFAULT NULL; IF $Data IS NOT NULL THEN SET $Result = CONCAT(HEX(SUBSTRING($Data,4,1)),HEX(SUBSTRING($Data,3,1)),HEX(SUBSTRING($Data,2,1)), HEX(SUBSTRING($Data,1,1)) , '-', HEX(SUBSTRING($Data,6,1)),HEX(SUBSTRING($Data,5,1)),'-', HEX(SUBSTRING($Data,8,1)) , HEX(SUBSTRING($Data,7,1)),'-', HEX(SUBSTRING($Data,9,2)),'-',HEX(SUBSTRING($Data,11,6))); END IF; RETURN $Result; END
CREATE FUNCTION `UUIDTOBIN`() RETURNS binary(16) BEGIN DECLARE my_uuid char(36); SET my_uuid = UUID(); RETURN CONCAT(UNHEX(LEFT(my_uuid,8)),UNHEX(MID(my_uuid,10,4)),UNHEX(MID(my_uuid,15,4)),UNHEX(MID(my_uuid,20,4)),UNHEX(RIGHT(my_uuid,12))); END CREATE FUNCTION `BINTOUUID`(UUID BINARY(16)) RETURNS char(36) BEGIN RETURN CONCAT(HEX(LEFT(uuid,4)),'-', HEX(MID(uuid,5,2)),'-', HEX(MID(uuid,7,2)),'-',HEX(MID(uuid,9,2)),'-',HEX(RIGHT(uuid,6))); END