测试(从头开始走一遍流程):
1)创建Person表:
[sql] view plaincopy
- drop table person;
- create table person(
- id int NOT NULL AUTO_INCREMENT primary key,
- name varchar(8) not null,
- sex bit,
- age int check(age > 0 and age < 200),
- addr varchar(100) default ‘‘ not null
- );
- select * from person;
此时Person表为空
2)创建countPerson表
[sql] view plaincopy
- drop table if exists countPerson;
- create table countPerson(
- totalnum int default 0
- );
- insert into countPerson(totalnum) values(0);
- select * from countPerson;
此时初始totalNum = 0
3) 创建触发器
[sql] view plaincopy
- DROP TRIGGER IF EXISTS insertTrigger;
- delimiter //
- CREATE TRIGGER insertTrigger
- AFTER INSERT ON person
- FOR EACH ROW
- BEGIN
- update countPerson set totalNum = totalNum + 1;
- END;//
4)在Person表中添加记录insert
[sql] view plaincopy
- insert into person(name, sex, age, addr) values(‘Jeremy‘, 1, 20, ‘SH‘);
- insert into person(name, sex, age, addr) values(‘Hellon‘, 1, 22, ‘SH‘);
- select * from person;
此时Person表中记录如下,
5)看一下触发器有没有起作用
[sql] view plaincopy
- select * from countPerson;
发现有作用了。
附:
此外使用下面语句可以看到数据库的触发器信息
[sql] view plaincopy
- SELECT * FROM information_schema.`TRIGGERS`;
|