Home  >  Article  >  Database  >  How can I implement combined INSERT and UPDATE triggers in MySQL?

How can I implement combined INSERT and UPDATE triggers in MySQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-22 10:07:24980browse

How can I implement combined INSERT and UPDATE triggers in MySQL?

Combining INSERT and UPDATE Triggers in MySQL

It is possible to trigger a MySQL trigger for both the insert and update events of a table. However, you will need to create two separate triggers.

To create a trigger that executes on both insert and update events, follow these steps:

  1. Create a stored procedure containing the common code for the trigger.
  2. Create two triggers that call the stored procedure, specifying the appropriate events for each trigger.

Example:

1. Create Common Stored Procedure:

CREATE PROCEDURE common_trigger_procedure()
BEGIN
    -- Code to execute for both insert and update events
END //

2. Create Triggers:

CREATE TRIGGER my_insert_trigger
AFTER INSERT ON `table`
FOR EACH ROW
BEGIN
    CALL common_trigger_procedure();
END //

CREATE TRIGGER my_update_trigger
AFTER UPDATE ON `table`
FOR EACH ROW
BEGIN
    CALL common_trigger_procedure();
END //

By using this approach, you can avoid repeating the same code in multiple triggers, ensuring code maintainability and consistency.

The above is the detailed content of How can I implement combined INSERT and UPDATE triggers 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