Home >Database >Mysql Tutorial >How to Handle Identical Trigger Logic for Insert and Update Events in MySQL?

How to Handle Identical Trigger Logic for Insert and Update Events in MySQL?

DDD
DDDOriginal
2024-11-12 16:54:021049browse

How to Handle Identical Trigger Logic for Insert and Update Events in MySQL?

MySQL Trigger for Both Insert and Update

In MySQL, it's not possible to create a single trigger that fires for both insert and update events on a table. Therefore, you'll need to create two separate triggers, one for each event.

However, if the trigger code is the same for both insert and update events, you can move the common code into a stored procedure and have the triggers call the procedure instead. This approach allows you to avoid repeating the same code in multiple triggers.

Here's an example of how you can do this:

Create the stored procedure:

CREATE PROCEDURE common_trigger_code()
BEGIN
    -- Insert or update some data...
END //

Create the insert trigger:

CREATE TRIGGER insert_trigger
AFTER INSERT ON `table`
FOR EACH ROW
CALL common_trigger_code();

Create the update trigger:

CREATE TRIGGER update_trigger
AFTER UPDATE ON `table`
FOR EACH ROW
CALL common_trigger_code();

This solution ensures that the common code is only written once and can be easily updated in the future.

The above is the detailed content of How to Handle Identical Trigger Logic for Insert and Update Events in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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