触发器是一种特殊的存储过程,它在插入,删除或者修改特定表中的数据时触发执行,它比数据库本身标准的功能有更精细和更复杂的数据控制能力。
它具有这样的特征:
监视地点:一般就是表名
监视事件:update/delete/insert
触发时间:after/before
触发事件:update/delete/insert
他不能直接被调用,是由数据库主动执行。
example1:
创建表tab1
drop table if exists tab1;
create table tab1(
tab1_id varchar(11)
);
创建表tab2
drop table if exists tab2;
create table tab2(
tab2_id varchar(11)
);
创建触发器:t_afterinsert_on_tab1
作用:增加tab1表记录后自动将记录增加到tab2表中
drop trigger if exists t_afterinsert_on_tab1;
create trigger t_afterinsert_on_tab1
after insert on tab1
for each row
begin
insert into tab2(tab2_id) values(new.tab1_id);
end;
测试一下
insert into tab1(tab1_id) values('0001');
看看结果select * from tab1;
select * from tab2;
example2:
创建触发器:t_afterdelete_on_tab1
作用:删除tab1表记录后自动将tab2表中对应的记录删去
drop trigger if exists t_afterdelete_on_tab1;
create trigger t_afterdelete_on_tab1
after delete on tab1
for each row
begin
delete from tab2 where tab2_id=old.tab1_id;
end;
测试一下
delete from tab1 where tab1_id='0001';
看看结果select * from tab1;
select * from tab2;
以上就是mysql高级八——触发器的使用的内容。