📜  不同类型的 MySQL 触发器(附示例)(1)

📅  最后修改于: 2023-12-03 15:21:31.161000             🧑  作者: Mango

不同类型的 MySQL 触发器(附示例)

MySQL 触发器是一种特殊的存储过程,它们可以在特定事件发生时自动执行。触发器可以用来对表进行约束、限制和过滤,以及自动记录日志和审计记录等操作。

以下是几种常见的 MySQL 触发器类型及其示例:

1. BEFORE 触发器

BEFORE 触发器是在执行 INSERT、UPDATE 或 DELETE 操作之前触发,可以在数据被修改之前对数据进行一些检查或修改。

示例:在执行 INSERT 操作之前对数据进行校验,如果数据重复则拒绝插入。

CREATE TRIGGER before_insert_trigger
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
  IF EXISTS (SELECT 1 FROM users WHERE email = NEW.email) THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Email already exists';
  END IF;
END;
2. AFTER 触发器

AFTER 触发器是在执行 INSERT、UPDATE 或 DELETE 操作之后触发,可以在数据被修改之后对数据进行一些检查或修改。

示例:在执行 INSERT 操作之后自动发送邮件通知。

CREATE TRIGGER after_insert_trigger
AFTER INSERT ON users
FOR EACH ROW
BEGIN
  DECLARE email_subject VARCHAR(255);
  DECLARE email_content VARCHAR(255);
  SET email_subject = 'New user registration';
  SET email_content = CONCAT('A new user (', NEW.email, ') has registered.');
  CALL send_email(NEW.email, email_subject, email_content);
END;
3. INSTEAD OF 触发器

INSTEAD OF 触发器是在执行 INSERT、UPDATE 或 DELETE 操作之前触发,但它能够修改被执行的操作,可以用来模仿对视图进行的 INSERT、UPDATE 或 DELETE 操作。

示例:在视图上创建 INSTEAD OF 触发器,可以在视图上执行 INSERT、UPDATE 或 DELETE 操作,实际上是对多个表进行操作。

CREATE VIEW customer_orders AS
SELECT c.customer_id, o.order_id, o.order_date, o.total
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id;

CREATE TRIGGER customer_orders_trigger
INSTEAD OF INSERT ON customer_orders
FOR EACH ROW
BEGIN
  INSERT INTO customers (customer_id, customer_name, customer_email)
  VALUES (NEW.customer_id,
  (SELECT customer_name FROM customer_details WHERE customer_id = NEW.customer_id),
  (SELECT customer_email FROM customer_details WHERE customer_id = NEW.customer_id));

  INSERT INTO orders (order_id, customer_id, order_date, total)
  VALUES (NEW.order_id, NEW.customer_id, NEW.order_date, NEW.total);
END;

以上是 MySQL 触发器的几种不同类型及其示例。通过使用不同类型的触发器可以实现更强大和灵活的数据操作和管理。