I have created this trigger to update the seq column. I have to keep track of the order of certain items in the table, but only if the liability_category_id = 1,2. So my ordering is tricky because any item with a liability_category_id = 3 I don’t need to track.
In my trigger, I’m querying to find the last entered seq number (using max(seq)), then turning around and updating the new entry with the seq + 1.
DELIMITER $$
USE `analysisdb`$$
DROP TRIGGER /*!50032 IF EXISTS */ `trigger_liability_detail_after_insert`$$
CREATE
/*!50017 DEFINER = 'admin'@'%' */
TRIGGER `trigger_liability_detail_after_insert` AFTER INSERT ON `liability_detail`
FOR EACH ROW BEGIN
DECLARE SortOrder INT;
IF NEW.liability_category_id = 1 OR NEW.liability_category_id = 2 THEN
SET SortOrder = (SELECT MAX(seq) FROM liability_detail WHERE analysis_id = new.analysis_id AND liability_category_id IN (1, 2));
UPDATE liability_detail SET seq = (SortOrder + 1) WHERE id = NEW.id;
END IF;
END;
$$
DELIMITER ;
However, when entering a new item, I get this error: Can’t update table ‘liability_detail’ in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Is there a better way to control the ordering of these items? My original thought was to simply set the first seq = 1, then seq = 2, etc. The ordering is reset for each new analysis_id though.
I think the workaround is to make this a before trigger and update the record being insert itself prior to insert.
So
That was a quick copy/paste, but it should be something along those lines.