MySQL触发器

触发器是由MySQL 的基本命令事件来触发某种特定操作,这些基本命令由insert、update、delete等事件触发某些特定操作。

创建单条执行语句的MySQL触发器:

create trigger trigger_name before | after insert | update | delete

on table_name for each row 

执行语句


demo1;(插入tb_studentinfo时先插入tb_log)

delimiter //

create trigger insert_log before insert

on tb_studentinfo for each row 

insert into tb_log(time) values(now());

//

delimiter;


创建多条执行语句的MySQL触发器:

create trigger trigger_name before | after insert | update | delete

on table_name for each row 

begin

执行语句;

执行语句;

end


demo1:

delimiter //

create trigger delete_time after delete

on tb_studentinfo for each row

begin

insert into tb_log(time) values(now());

insert into tb_opt(str) values("delete");

end

//

delimiter;

注意:对于相同的触发器事件如(insert,update,delete)before和after触发器只能各一个。


查看触发器:

show triggers;

//  查看到该库所有的触发器;

select * from information_schema.triggers;

select * from information_schema.triggers where trigger_name = 'trigger_names';

//  所有触发器都定义在information_schema库(默认存在的库)的triggers表中。

触发器按照:before、 insert | update | delete 操作 、after的顺序来执行。

注意:触发器中不能包含STARTTRANSCATION、COMMIT、ROLLBACK、CALL语句等。已经更新过的数据表是不能回滚的。

删除触发器:

DROP trigger trigger_name;

你可能感兴趣的:(MySQL触发器)