Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating trigger in mysql for generation UUID

Tags:

mysql

how can this throw an error when trying to create a trigger before insert in MySQL so that it generates new UUID for every input.

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

and here is my table

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

I must be doing something wrong.

like image 266
Thunder Avatar asked Dec 02 '13 21:12

Thunder


People also ask

Is UUID good for primary key?

UUIDs as primary key aren't a slam drunk, but do have some advantages: The fact that they're random means that they don't rely on a single sequence to be generated. Multiple entities can generate IDs independently, but still store them to a shared data store without clobbering each other.

Does MySQL support UUID?

UUID() function in MySQLThis function in MySQL is used to return a Universal Unique Identifier (UUID) generated according to RFC 4122, “A Universally Unique Identifier (UUID) URN Namespace”. It is designed as a number that is universally unique.

Does mysql5 7 support triggers?

MySQL 5.7 does not support triggers using FOR EACH STATEMENT .


2 Answers

You can define that trigger in one statement, i.e.:

CREATE TRIGGER insert_guid BEFORE INSERT ON guid_tool FOR EACH ROW SET NEW.guid_key = UUID();
like image 194
Paul Vargas Avatar answered Oct 10 '22 02:10

Paul Vargas


As mentioned by @mabi in the comments - you have a syntax error with the brackets. The following modified code works for me:

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

Testing it out:

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)
like image 26
madebydavid Avatar answered Oct 10 '22 01:10

madebydavid