4

I have an industrial system that logs alarms to a remotely hosted MySQL database. The industrial system inserts a new row whenever a property of the alarm changes (such as the time the alarm was activated, acknowledged or switched off) into a table named 'alarms'.

I don't want multiple records for each alarm, so I have set up two database triggers. The first trigger mirrors each new record to a second table, creating/updating rows as required. The second table ('alarm_display') has the 'Tag' column set as the primary key. The 'alarm' table has no primary key. The code for this trigger is:

CREATE TRIGGER `mirror_alarms` BEFORE INSERT ON `alarms`
  FOR EACH ROW 
    INSERT INTO `alarm_display` (Tag,...,OffTime) 
    VALUES (new.Tag,...,new.OffTime) 
    ON DUPLICATE KEY UPDATE OnDate=new.OnDate,...,OffTime=new.OffTime

The second trigger should execute after the first and (ideally) delete all rows from the alarms table. (I used the Tag property of the alarm because the Tag property never changes, although I suspect I could just use a 'DELETE FROM alarms WHERE 1' statement to the same effect).

CREATE TRIGGER `remove_alarms` AFTER INSERT ON `alarms`
  FOR EACH ROW DELETE FROM alarms WHERE Tag=new.Tag

My problem is that the second trigger doesn't appear to run, or if it does, the second trigger doesn't delete any rows from the database.

So here's the question: why does my second trigger not do what I expect it to do?

1 Answer 1

6

The explanation can be read here: http://dev.mysql.com/doc/refman/5.0/en/stored-program-restrictions.html

Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

This is your problem and your trigger ends with error #1442.

The table alarms is already being used by the statement that invoked your trigger (the insert). This essentially means you cannot modify alarms with a delete trigger.

Cheers!

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Thanks! I was hoping to keep everything in SQL, but I think I'll set up a cron job to periodically clear out the database :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.