定义语法:
create trigger 名称
before/after insert/update/delete on 表名
begin
触发器执行语句
end
准备数据一:
create table emp
as
select id,name,salary from emploee
准备数据二:
create table emp_back
as
select * from emp where 1=2
1)新建触发器,实现插入数据后,往备份库也插入数据
create trigger insert_emp_message
after insert on emp
for each row
begin
insert into emp_back values(new.id,new.name,new.salary);
end
验证:
insert into emp values(202,'piter',3000)
select * from emp
select * from emp_back
2)新建触发器,实现数据删除前,往备份库也插入数据
create trigger delete_emp_message
before delete on emp
for each row
begin
insert into emp_back values(old.id,old.name,old.salary);
end
验证:
delete from emp where id=201
select * from emp
select * from emp_back
3)查看触发器
show create trigger insert_emp_message
show triggers;
4)删除触发器
drop trigger delete_emp_message
注:
1)触发器的优点是保持数据的完整性,缺点是表结构修改后,容易忘记触发器事件导致报错后排查问题复杂。 工作中根据具体情况使用。