MySQL触发器简单用法示例

时间:2022-08-26 16:50:51

本文实例讲述了MySQL触发器简单用法。分享给大家供大家参考,具体如下:

mysql触发器和存储过程一样,是嵌入到mysql的一段程序,触发器是由事件来触发的,这些事件包括,INSERT,UPDATE,DELETE,不包括SELECT

创建触发器

?
1
CREATE TRIGGER name,time,event ON table_name FOR EACH ROW trigger_stmt

例如

复制代码 代码如下:
CREATE TRIGGER ins_sum BEFORE INSERT ON account FOR EACH ROW SET @sum = @sum + NEW.amount

 

有多个执行语句的触发器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
CREATE TABLE test1(a1 INT);
CREATE TABLE test2(a2 INT);
CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE TABLE test4(
  a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  b4 INT DEFAULT 0
);
DELIMITER //
CREATE TRIGGER testref BEFORE INSERT ON test1
  FOR EACH ROW BEGIN
    INSERT INTO test2 SET a2 = NEW.a1;
  DELETE FROM test3 where a3 = NEW.a1;
    UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
  END
  //
DELIMITER ;
INSERT INTO test3(a3) VALUES (NULL), (NULL), (NULL), (NULL), (NULL), (NULL),(NULL), (NULL), (NULL), (NULL), (NULL), (NULL);
INSERT INTO test4(a4) VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0);
//开始测试
INSERT INTO test1 VALUES (1), (3), (1), (7), (1), (8), (4), (4);

查看触发器

?
1
2
SHOW TRIGGERS \G; //查看所有
SELECT * FROM information_schema.TRIGGERS where TRIGGER_NAME = 'testref';

删除触发器

?
1
DROP TRIGGER testref;

综合案例

步骤1:创建persons表

?
1
CREATE TABLE persons (name VARCHAR(40), num int);

步骤2:创建一个销售额表sales

?
1
CREATE TABLE sales (name VARCHAR(40), sum int);

步骤3:创建一个触发器

?
1
2
CREATE TRIGGER num_sum AFTER INSERT ON persons
FOR EACH ROW INSERT INTO sales VALUES (NEW.name,7*NEW.num);

步骤4:向persons表中插入记录

?
1
2
3
INSERT INTO persons VALUES ('xiaoxiao',20),('xiaohua',69);
SELECT * FROM persons;
SELECT *FROM sales;

希望本文所述对大家MySQL数据库计有所帮助。

原文链接:http://www.cnblogs.com/mr-amazing/p/4679743.html