S
S
sbh2020-05-30 12:59:43
MySQL
sbh, 2020-05-30 12:59:43

How to update records in a BEFORE INSERT trigger?

There is a table:

ID
LOGIN_ID
Start
End
Session_ID


the Session_ID field has an index "Unique"
there is a script which parses the data and pours them into the table.
It is necessary to update the End field when there is a record with Session_ID in the table if the new value is greater than the previous one.
I implemented it using the Before insert trigger, but I get an error:
""Can't update table 'data' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.""

Perhaps somehow differently It is possible to implement such behavior, the question is how?

Trigger:
CREATE TRIGGER `CHECK_SESSION` BEFORE INSERT ON `data`
 FOR EACH ROW BEGIN
SET @myVar1 = (SELECT `START` from `data` where `SESSION_ID` = NEW.SESSION_ID and `END` < new.END);
IF(@myVar1 IS NOT NULL) THEN 
BEGIN
  Insert into `data`(`LOGIN_ID`, `IP`, `SESSION_ID`, `SESSION_START`, `SESSION_TIMESTAMP`) values (new.LOGIN_ID, new.IP, new.SESSION_ID, new.SESSION_START, new.SESSION_TIMESTAMP) ON DUPLICATE KEY UPDATE `SESSION_TIMESTAMP` = new.SESSION_TIMESTAMP;
END;
END IF;
SET @myVar2 = (SELECT `START` from `data` where `SESSION_ID` = NEW.SESSION_ID and `END` > new.END);
IF(@myVar2 IS NOT NULL) THEN 
BEGIN
  declare msg varchar(128);
  set msg = 'Filter!';
    signal sqlstate '45000' set message_text = msg;
END;
END IF;
END

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-05-30
@sbh

INSERT
  INTO `table` (`LOGIN_ID`, `Start`, `End`, `Session_ID`)
  VALUES (:loginId, :start, :end, :sessionId)
  ON DUPLICATE KEY UPDATE `End` = GREATEST(`End`, :end)

And in triggers, you cannot change the table on which the trigger fired. Otherwise, there would be an infinite cyclic firing of the trigger.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question