Home > Database > Mysql Tutorial > How Can I Prevent 'Can't update table in stored function/trigger' Errors When Using After Update Triggers?

How Can I Prevent 'Can't update table in stored function/trigger' Errors When Using After Update Triggers?

Linda Hamilton
Release: 2024-12-26 22:28:14
Original
685 people have browsed it

How Can I Prevent

Trigger Updates After Same Table Update

In database systems, triggers are used to automatically perform specific actions when certain events occur within a table. One common challenge arises when attempting to update the same table from within a trigger after an update on that table.

Consider the following trigger:

CREATE TRIGGER upd_total_votes AFTER UPDATE ON products_score
FOR EACH ROW
    UPDATE
        products_score 
    SET
        products_score.votes_total =
            (SELECT
                 (votes_1 + votes_2 + votes_3 + votes_4 + votes_5)
             FROM
                 products_score
             WHERE
                 id = new.id);
Copy after login

When trying to update the table as follows:

UPDATE products_score SET votes_1 = 5 WHERE id = 0;
Copy after login

the trigger fails with the error:

#1442 - Can't update table 'products_score' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Copy after login

To resolve this, the trigger must be modified to execute before the update event, rather than after. This allows the trigger to update the table before the original update statement is applied:

CREATE TRIGGER upd_total_votes BEFORE UPDATE ON products_score
FOR EACH ROW
BEGIN
    SET new.votes_total = new.votes_1 + new.votes_2 + new.votes_3 + new.votes_4 + new.votes_5;
END;
Copy after login

With this modification, updating the table as before will successfully trigger the votes_total column to be updated.

The above is the detailed content of How Can I Prevent 'Can't update table in stored function/trigger' Errors When Using After Update Triggers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template