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