I’m using a trigger in MySQL to do the following:
When I add a new client to the client table, it should create a set of entries in a ‘Client-Type’ table, linking the client id to a set of type ids (client1, type1 client1, type2) etc…
However, the database is inserting the entry for the last type twice when the trigger is run. So the last two entries are (client1, type9 client1, type9).
The trigger code is as follows:
AFTER INSERT ON `nmsTicket`.`client`
FOR EACH ROW
BEGIN
DECLARE done BOOLEAN DEFAULT 0;
DECLARE a CHAR(2);
DECLARE types CURSOR
FOR
SELECT typeID FROM type;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
OPEN types;
REPEAT
FETCH types INTO a;
INSERT INTO clientType(id_type, id_client) VALUES (a,new.idClient);
UNTIL done END REPEAT;
CLOSE types;
I’ve looked it over a few times, but I can’t see why it would be exhibiting this behaviour; all the entries before the last one work fine.
Any pointers?
I’m not sure why you’re using a cursor in your trigger – this should be avoided unless you absolutely need one (see here for example Optimal MySQL settings for queries that deliver large amounts of data?)
The following is a simplified example (minus referential integrity) which uses a cross join instead of a cursor. In addition you’ll notice I’m not using a surrogate primary key on the client_types table but a composite one instead which better enforces data integrity.
Schema
Testing
Hope this helps 🙂