S
S
sbh2020-05-06 14:13:06
MySQL
sbh, 2020-05-06 14:13:06

How to use a trigger not to insert a record, but to update the old one?

It is necessary to check whether there is a record with certain parameters using the BEFORE INSERT trigger, and if it is, then do not insert a new record, but update the found one.

Here's the trigger:

SET @myVar1 = (SELECT `SESSION_START` from `radius` where `SESSION_START` = NEW.SESSION_START and `LOGIN_ID` = new.LOGIN_ID);
IF(@myVar1 IS NULL) THEN 
BEGIN
Insert into `radius`(`LOGIN_ID`, `IP`, `SESSION_ID`, `SESSION_START`, `SESSION_TIMESTAMP`) values (new.LOGIN_ID, new.IP, new.SESSION_ID, new.SESSION_START, new.SESSION_TIMESTAMP);
END;
ELSE
UPDATE `radius` SET `SESSION_TIMESTAMP` = new.SESSION_TIMESTAMP WHERE `SESSION_START` = new.SESSION_START;
END IF;


Error when inserting data
Can't update table 'radius' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-05-06
@sbh

Look towards
INSERT INTO
ON DUPLICATE KEY UPDATE

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question