Mysql 简明教程

MySQL - Before Insert Trigger

正如我们已经了解过的, Trigger 被定义为对执行的事件的响应。在 MySQL 中,触发器被称为特殊存储过程,因为它不需要像其他存储过程那样显式调用。发生所需事件时,触发器会自动起作用。这些事件包括执行 SQL 语句,如 INSERT、UPDATE 和 DELETE 等。

As we have already learned, a Trigger is defined as a response to an event performed. In MySQL, a trigger is called a special stored procedure as it does not require to be invoked explicitly like other stored procedures. The trigger acts automatically whenever the desired event is fired. These events include executing SQL statements like INSERT, UPDATE and DELETE etc.

MySQL Before Insert Trigger

Before Insert 触发器是 MySQL 数据库支持的行级触发器。顾名思义,此触发器在值被插入数据库表之前立即执行。

The Before Insert Trigger is a row-level trigger supported by the MySQL database. As its name suggests, this trigger is executed right before a value is being inserted into a database table.

每当在数据库中查询 INSERT 语句时,此触发器都会自动首先执行,然后才将值插入表中。

Whenever an INSERT statement is queried in the database, this Trigger is automatically executed first and then only the value is inserted into the table.

Syntax

这是在 MySQL 中创建 BEFORE INSERT 触发器的语法 −

Following is the syntax to create the BEFORE INSERT trigger in MySQL −

CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name FOR EACH ROW
BEGIN
   -- trigger body
END;

Example

让我们看一个演示 BEFORE INSERT 触发器示例。在此,我们正在使用以下查询创建包含机构内学生详细信息的新表 STUDENT −

Let us see an example demonstrating the BEFORE INSERT trigger. In here, we are creating a new table STUDENT which contains the details of students in an institution, using the following query −

CREATE TABLE STUDENT(
   Name varchar(35),
   Age INT,
   Score INT,
   Grade CHAR(10)
);

使用以下 CREATE TRIGGER 语句,在 STUDENT 表上创建一个新触发器 sample_trigger 。在这里,我们检查每个学生的成绩并为他们分配合适的等级。

Using the following CREATE TRIGGER statement, create a new trigger sample_trigger on the STUDENT table. Here, we are checking the score of each student and assigning them with a suitable grade.

DELIMITER //
CREATE TRIGGER sample_trigger
BEFORE INSERT ON STUDENT FOR EACH ROW
BEGIN
IF NEW.Score < 35 THEN SET NEW.Grade = 'FAIL';
ELSE SET NEW.Grade = 'PASS';
END IF;
END //
DELIMITER ;

使用如下所示的常规 INSERT 语句,将值插入 STUDENT 表 −

Insert values into the STUDENT table using the regular INSERT statement as shown below −

INSERT INTO STUDENT VALUES
('John', 21, 76, NULL),
('Jane', 20, 24, NULL),
('Rob', 21, 57, NULL),
('Albert', 19, 87, NULL);

Verification

要验证触发器是否已执行,请使用 SELECT 语句显示 STUDENT 表 −

To verify if the trigger has been executed, display the STUDENT table using the SELECT statement −

Before Insert Trigger Using a Client Program

除了创建或显示触发器,我们还可以使用客户端程序执行“Before Insert 触发器”语句。

In addition to create or show a trigger, we can also Perform the "Before Insert trigger" statement using a client program.

Syntax

Example

以下是这些程序 −

Following are the programs −