Home >Database >Mysql Tutorial >Mysql触发器

Mysql触发器

WBOY
WBOYOriginal
2016-06-07 16:14:381150browse

触发器,顾名思义,基于某具体的DML语句的触发或执行,来执行一个动作。mysql触发器在6个不同的集成点进行定义: before insert after insert before update after update before delete after delete 每个点只能定义一个触发器,触发器只可以应用在for each

触发器,顾名思义,基于某具体的DML语句的触发或执行,来执行一个动作。mysql触发器在6个不同的集成点进行定义:
before insert
after insert
before update
after update
before delete
after delete
每个点只能定义一个触发器,触发器只可以应用在for each row上,没有每个语句级的功能。
也没有代替触发器的语法。


触发器的语法:
create trigger   //定义触发器的名称
before |after insert|update|delete on

//定义触发器与哪个表关联以及何时执行触发器
for each row //必需的语法,表明触发器会因每行的执行查询而触发
//指定要执行的语句

例如:

delimiter //

create trigger trigger_test_bri

before insert on trigger_test

for each row

insert into logger(id,action,time) values (NEW.id, 'Insert', NOW());

//

create trigger trigger_test_ari

after insert on trigger_test

for each row

insert into logger(id,action,time) values (NEW.id, 'Insert', NOW());

//

delimiter ;

现在如果向表trigger_test中执行插入语句,就会在logger表中生成两条记录,一个ID为0,一个ID为trigger_test中插入的ID。



更新触发器:

添加before update或者after update触发器并测试update语法:

create trigger trigger_test_bru

before update on trigger_test

for each row

insert into logger(id,action,time) values (OLD.id, 'Update', NOW());

//

create trigger trigger_test_aru

after update on trigger_test

for each row
insert into logger(id,action,time) values(NEW.id, 'Update', NOW());

//

update trigger_test set id=id+10 where id=1;

现在查看logger表,发现多了两条数据。

如果拥有super权限,就可以指定一个用户作为触发器的定义者。默认情况下,当执行触发器时,当前用户的权限会用于底层表。可以改变这些默认设置,使特定的用户可以执行这些操作。
create [definer | current_user] trigger

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn