characteristic 说明:
① DETERMINISTIC:相同的输入参数总是产生相同的结果
② NO SQL :不包含 SQL 语句
③ READS SQL DATA:包含读取数据的语句,不包含写入数据的语句
用存储函数求 1~n 的累加和
# 输入参数不能写【in】,会报错
# create function sum_func(in n int) # 会报错
create function sum_func(n int) # RIGHT
returns int DETERMINISTIC
begin
declare sum int default 0;
while(n > 0) do
set sum := sum + n;
set n := n - 1;
end while;
return sum;
end;
# 调用存储函数
select sum_func(100);
insert/update/delete
之前 (BEFORE) 或之后 (AFTER),触发并执行触发器中定义的 SQL 语句集合OLD
和 NEW
可引用触发器中发生变化的记录 通过触发器记录 tb_user
表的数据变更日志,将变更日志插入到日志表 user_logs
中。包含增加,修改, 删除的日志
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;
insert 触发器:
# 创建触发器(insert)
create trigger tb_user_insert_trigger
after insert on tb_user for each row
begin
insert into user_logs values (null, 'insert', now(), new.id, concat(new.id, '_,_', new.name, '_,_', new.email));
end;
# 查看触发器
show triggers;
select * from user_logs;
insert into tb_user values (null, '陈铭酒', '19111658988', '[email protected]', '医学', 25, '男', 6, now());
update触发器:
# 查看触发器
show triggers;
drop trigger tb_user_update_trigger;
# 创建触发器(update)
create trigger tb_user_update_trigger
after update on tb_user for each row
begin
insert into user_logs values (null, 'update', now(), new.id, concat('前: profession=', old.profession,
' 后:', 'profession=', new.profession));
end;
update tb_user set profession = '肿瘤学' where `name` = '陈铭酒';
update tb_user set profession = '母猪产后护理' where id >= 20;
delete 触发器:
# 创建触发器(delete)
create trigger tb_user_delete_trigger
after delete on tb_user for each row
begin
insert into user_logs values (null, 'delete', now(), old.id, concat('被删除: name=', old.name));
end;