在mysql中创建触发器以生成UUID

时间:2013-12-02 21:02:56

标签: mysql

如何在插入MySQL之前尝试创建触发器时抛出错误,以便为每个输入生成新的UUID。

CREATE TRIGGER insert_guid 
BEFORE INSERT ON guid_tool (FOR EACH  ROW 
BEGIN 
  SET NEW.guid_key = UUID()); 
END;

这是我的表

create table guid_tool (
    ID INT NOT NULL AUTO_INCREMENT, 
    guid_key CHAR(40) NOT NULL, 
    PRIMARY KEY(ID)
) CHARSET=LATIN1;

我一定是做错了。

2 个答案:

答案 0 :(得分:6)

正如@mabi在评论中所提到的 - 括号中存在语法错误。以下修改后的代码适用于我:

DELIMITER #
CREATE TRIGGER insert_guid 
BEFORE INSERT ON guid_tool
FOR EACH  ROW 
BEGIN 
    SET NEW.guid_key = UUID(); 
END;
#
DELIMITER ;

测试出来:

mysql> INSERT INTO guid_tool (ID) VALUES (1);
Query OK, 1 row affected, 1 warning (0.04 sec)

mysql> SELECT * FROM guid_tool;
+----+--------------------------------------+
| ID | guid_key                             |
+----+--------------------------------------+
|  1 | a0467ebf-5c4f-11e3-903a-6cccbb4423e3 |
+----+--------------------------------------+
1 row in set (0.00 sec)

答案 1 :(得分:2)

您可以在一个语句中定义该触发器,即:

CREATE TRIGGER insert_guid BEFORE INSERT ON guid_tool FOR EACH ROW SET NEW.guid_key = UUID();