Sorry to ask this question again as there is a lot on the forum about this issue. But I hope my problem is different from others. Sorry for my bad English.
First I have 2 tables (parent table and child table) Parent(Position)
loc_id | loc_size |
---|---|
1 | 100 |
2 | 75 |
Children (area)
ar_id | ar_loc_id | ar_size |
---|---|---|
1 | 2 | 35 |
2 | 2 | 40 |
This is my post-delete trigger.
CREATE TRIGGER after_delete_area_location AFTER DELETE ON area FOR EACH ROW BEGIN UPDATE location SET loc_size = loc_size + old.ar_size WHERE loc_id=old.ar_loc_id END;
For example, if I want to delete ar_id = '2', then ar_size will be updated in position loc_size.
Since the loc_size value is "0", the value will be 40 after the trigger runs.
The problem is that the trigger is not running correctly, after the trigger runs loc_size is not updated at all, just the "0" value.
Am I missing something or something is happening because it simply doesn't work.
Please help me solve this problem. Thank you very much.
I see there is nothing wrong with your trigger. I tested it and it's working. To make it complete, I added an insert trigger on table
region
.As you can see, in both insert and delete operations, the values are updated accordingly.
-- Update from here --
This is an enhanced version of trigger
after_insert_area_location
where I will demonstrate the newly added IF statement to maintain data integrity. Note that theSIGNAL
statement is used to raise an error, which acts as a warning message and terminates the operation.As you can see, the
SIGNAL
statement in the trigger'sIF
statement raised an error with the SQL_STATE code77777
and the message: Is Preliminary set. This will undo the changes made since the new row was inserted.In short, we can use IF statements in triggers to have some control over the data flow. The SIGNAL statement can be used to intentionally invoke an error to stop/undo the execution of a trigger and start the action of a trigger. As mentioned above, not only is the
UPDATE
in the trigger not executed, theinsert
statement that triggered the trigger is also undone.