Home > Database > Mysql Tutorial > body text

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

DDD
Release: 2024-11-12 16:54:02
Original
1002 people have browsed it

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 //
Copy after login

Create the insert trigger:

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

Create the update trigger:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template