我可以在 mysql 的一个触发器声明中定义多个事件吗?

2022-01-01 00:00:00 sql mysql triggers

这是我的要求,我有一个 mysql 表,任何更改(插入/删除/更新)都应该以完全相同的方式处理.根据mysql文档创建触发器语法如下:

Here is my requirement, I have a mysql table on which any change (insert/delete/update) should be handled in exactly same way. According to mysql documentation create trigger syntax is as follows:

    CREATE
     [DEFINER = { user | CURRENT_USER }]
     TRIGGER trigger_name
     trigger_time **trigger_event**
     ON tbl_name FOR EACH ROW
     trigger_body

当我尝试放置多个事件时,会抛出语法错误.一种解决方案是我可以编写一个过程和 3 个触发器(每个事件一个)并从所有触发器调用相同的过程.

When I'm trying to put more than one event, its throwing syntax error. One solution is I can write one procedure and 3 triggers (one for each event) and call the same procedure from all the triggers.

对此有什么复杂的解决方案吗??

Is there any sophisticated solution for this ??

推荐答案

没有.在 MySQL 中,触发器用于单个 trigger_event.触发器必须是 BEFOREAFTERINSERTUPDATEDELETE.

No. In MySQL, a trigger is for a single trigger_event. A trigger has to be either BEFORE or AFTER and one of INSERT, UPDATE, DELETE.

如果我们有很多跨触发器事件共享的逻辑(需要在多个触发器中复制的逻辑),我们可以编写/创建一个 PROCEDURE 来封装该逻辑,并从多个触发器的主体中调用该过程触发器.

If we have lots of logic that is shared across the trigger events (logic that would need to be duplicated in multiple triggers), we can write/create a PROCEDURE to encapsulate that logic, and call that procedure from the body of multiple triggers.

相关文章