wpearse
wpearse

Reputation: 2422

SQL trigger to delete rows from database

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?

Upvotes: 4

Views: 3836

Answers (1)

Lachezar Balev
Lachezar Balev

Reputation: 12021

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!

Upvotes: 6

Related Questions