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.
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.
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.
MySQL 5.7 does not support triggers using FOR EACH STATEMENT .
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();
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With