MySQL触发器简单用法示例
本文实例讲述了MySQL触发器简单用法。分享给大家供大家参考,具体如下:
mysql触发器和存储过程一样,是嵌入到mysql的一段程序,触发器是由事件来触发的,这些事件包括,INSERT,UPDATE,DELETE,不包括SELECT
创建触发器
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
有多个执行语句的触发器
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);
查看触发器
SHOW TRIGGERS \G; //查看所有 SELECT * FROM information_schema.TRIGGERS where TRIGGER_NAME = 'testref';
删除触发器
DROP TRIGGER testref;
综合案例
步骤1:创建persons表
CREATE TABLE persons (name VARCHAR(40), num int);
步骤2:创建一个销售额表sales
CREATE TABLE sales (name VARCHAR(40), sum int);
步骤3:创建一个触发器
CREATE TRIGGER num_sum AFTER INSERT ON persons FOR EACH ROW INSERT INTO sales VALUES (NEW.name,7*NEW.num);
步骤4:向persons表中插入记录
INSERT INTO persons VALUES ('xiaoxiao',20),('xiaohua',69); SELECT * FROM persons; SELECT *FROM sales;
更多关于MySQL相关内容感兴趣的读者可查看本站专题:《MySQL查询技巧大全》、《MySQL事务操作技巧汇总》、《MySQL存储过程技巧大全》、《MySQL数据库锁相关技巧汇总》及《MySQL常用函数大汇总》
希望本文所述对大家MySQL数据库计有所帮助。
相关推荐
debugjoker 2020-06-17
zjuwangleicn 2020-06-25
昊 2020-06-16
sunnyxuebuhui 2020-06-14
hanshangzhi 2020-06-14
ncomoon 2020-06-14
hanshangzhi 2020-06-12
wudaokouer 2020-04-16
一昕之代码 2020-02-20
李轮清 2020-05-11
URML 2020-05-10
nimeijian 2020-05-06
lpfvip00 2020-04-26
lt云飞扬gt 2020-04-21
书弋江山 2020-04-19
dayi 2020-04-11
daillo 2020-04-07
Accpcjg 2020-03-05