1、什么是触发器

触发器是与表有关的命名数据库对象。触发器由事件来触发某个操作。

触发器是特殊的存储过程,触发器不需要call语句来调用,也不需要手工启动,只需要确定一个预定义的事件发生的时候,就会被MySQL自动调用。

2、创建触发器

  1》创建只有一个执行语句的触发器

//trigger_time触发的时机,可以指定before或after;
//trigger_event标识触发事件,包括insert、update、delete;
//trigger_stmt是触发器执行语句。
create trigger trigger_name trigger_time trigger_event
on tb_name
for exch row trigger_stmt
mysql> create table account(num int,amount decimal(10,2));
Query OK, 0 rows affected (0.03 sec) mysql> create trigger ins_num before insert
-> on account
-> for each row set @sum=@sum+NEW.amount;
Query OK, 0 rows affected (0.02 sec) mysql> set @sum=0;
Query OK, 0 rows affected (0.00 sec) mysql> insert into account values(1,1.00),(2,2.00);
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 0 mysql> select @sum;
+------+
| @sum |
+------+
| 3.00 |
+------+
1 row in set (0.00 sec) mysql>

2》创建有多个执行语句的触发器

create trigger trigger_name trigger_time trigger_event
on tb_name for exch row
begin
...
end
mysql> create table t1(a1 int);
Query OK, 0 rows affected (0.03 sec) mysql> create table t2(a2 int);
Query OK, 0 rows affected (0.01 sec) mysql> delimiter //
mysql> create trigger trigger_insert_t1 before insert
-> on t1 for each row
-> begin
-> insert into t2 values(NEW.a1);
-> end//
Query OK, 0 rows affected (0.01 sec) mysql> delimiter ;
mysql> insert into t1 values(233);
Query OK, 1 row affected (0.00 sec) mysql> select * from t1;
+------+
| a1 |
+------+
| 233 |
+------+
1 row in set (0.00 sec) mysql> select * from t2;
+------+
| a2 |
+------+
| 233 |
+------+
1 row in set (0.00 sec) mysql>

3、查看触发器,2种方式

1》show triggers

show triggers;

2》在triggers表中查看触发器信息。

select * from information_schema.triggers where condition;

4、触发器的使用

在insert、update、delete事件中对数据检查等。

5、删除触发器

drop trigger [schema_name.]trigger_name

最新文章

  1. Xcode8以及iOS10问题总结!
  2. fsck检查和修复文件系统
  3. java开发之多线程需要学习和理解的东西
  4. Hexo中添加emoji表情
  5. Core Bluetooth下实现两个设备进行互联
  6. Swift的初始化方法
  7. 几行实现圆形头像,以及一些常见需求形状自定义ImageView组件
  8. 浩哥解析MyBatis源码(九)——Type类型模块之类型处理器注册器(TypeHandlerRegistry)
  9. RestTemplate通过InputStreamResource上传文件
  10. Codeforces 959F Mahmoud and Ehab and yet another xor task 线性基 (看题解)
  11. python学习之第八篇——字典嵌套之字典中嵌套字典
  12. 手机连接wamp网页
  13. unity 3d音效如何设置?,近大远小
  14. Centos 7.x临时的网络与路由配置
  15. 使用对象作为hashMap的键,需要覆盖hashcode和equals方法
  16. Debian&&ubuntu系安装MegaCli
  17. JavaScript总结(六)
  18. Elasticsearch技术解析与实战(二)文档的CRUD操作
  19. 170704、springboot编程之CommandLineRunner
  20. HRBUST1310 火影忍者之~鸣人 2017-03-06 16:01 104人阅读 评论(0) 收藏

热门文章

  1. 给DEDECMS广告管理中增加图片上传功能
  2. 上传200G文件
  3. sh_02_快速体验
  4. cvtColor
  5. 苹果cms开启防红跳转后,提示模板文件不存在解决方法
  6. 在cmd上执行关于java的反编译
  7. (67)c++后台开发
  8. 交互式数据可视化-D3.js(二)选择集和数据
  9. linux 目录介绍
  10. __file__, sys._getframe().f_lineno 当前文件的行号