SQL之触发器


一、介绍

触发器是与表有关的数据库对象,指在insert/update/delete之前或之后,触发并执行触发器中定义的SQL语句集合。触发器的这种特性可以协助应用在数据库端确保数据的完整性,日志记录,数据校验等操作。
使用别名OLD和NEW 来引用触发器中发生变化的记录内容,这与其他的数据库是相似的。现在触发器还只支持行级触发,不支持语句级触发。
在这里插入图片描述

二、触发器语法

创建

CREATE TRIGGER trigger_name
BEFORE/AFTER INSERT/UPDATE/DELETE
ON tbl_name FOR EACH ROW--行级触发器
BEGIN
	trigger_stmt ;
END;

查看

SHOW TRIGGERS ;

删除

DROP TRIGGER [schema_name.]trigger_name;
--如果没有指定schema_name,默认为当前数据库。

1.案例

通过触发器记录user表的数据变更日志,将变更日志插入到日志表user_logs中,包含增加,修改,删除;
通过触发器记录USER表的数据变更日志,将变更日志插入到日志表User_Logs中,包含增加,修改,删除;

代码如下(示例):

create table user_logs(
	id int(11) not null auto_increment,
	operation varchar(20) not null comment '操作类型,insert/update/delete ' ,
	operate_time datetime not null comment '操作时间',
	operate_id int(11) not null comment'操作的ID',
	operate_params varchar(500) comment '操作参数',
	primary key(id)
)engine=innodb default charset=utf8;

-- 插入数据触发器
create trigger tb_user_insert_trigger
	after insert on user for each row
begin
	insert into user_logs(id,operation,operate_time,operate_id,operate_params) VALUES
(null, 'insert', now(), new.id, CONCAT('插入的数据内容为:id=', new.id,',name=', new.name,',phone=', NEW.phone,',email=',NEW.email,',profession=',NEW.profession));
end;

show triggers;

drop trigger tb_user_insert_trigger

insert into user(id, name, phone, email, profession) VALUES(25,'二皇子','18809091212' ,'erhuangzi@163.com','软件工程');

-- 更新
create trigger tb_user_update_trigger
	after update on user for each row
begin
	insert into user_logs(id,operation,operate_time,operate_id,operate_params) VALUES
(null, 'update', now(), new.id, CONCAT('更新前数据内容为:id=', old.id,',name=', old.name,',phone=', old.phone,',email=',old.email,',profession=',old.profession,
' | 更新后数据内容为:id=', new.id,',name=', new.name,',phone=', NEW.phone,',email=',NEW.email,',profession=',NEW.profession));
end;

update user set name = '大皇子' where id = '25';

-- 删除
create trigger tb_user_delete_trigger
	after delete on user for each row
begin
	insert into user_logs(id,operation,operate_time,operate_id,operate_params) VALUES
(null, 'delete', now(), old.id, CONCAT('删除数据内容为:id=', old.id,',name=', old.name,',phone=', old.phone,',email=',old.email,',profession=',old.profession
));
end;

delete from user where id = '25';

总结

可以在表数据进行INSERT、UPDATE、DELETE之前或之后触发

保证数据完整性、日志记录、数据校验
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十一*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值