您的位置:首页 > 数据库 > MySQL

mysql触发器

2013-09-28 02:08 1936 查看
1. 触发器的使用
create table customerHistory like customer;
alter table customerHistory add updated DATETIME; 
desc customerHistory;
创建一个名为trg_customer_history的触发器,在删除customer表中的数据时触发
create trigger trg_customer_history after delete on customer for each row
begin 
insert into customerHistory (mid,nam,birth,sex,updated) values(old.mid,old.nam,old.birth,old.sex,NOW());
end

select * from customer;
INSERT into customer values('A0001','小王','1990-1-2',0);
delete from customer where customer.mid = 'A0001';
select * from customerHistory;

查询创建的触发器
show triggers;

可以使用的关键词与事件的关系

inster
NEW
update
OLD 和 NEW
delete
OLD

2.游标

在创建存储过程,存储函数,以及触发器时,我们还必须掌握一种成为游标的功能。游标就是对select语句取得的结果进行一件一件的处理的功能。
使用游标时,先将select 语句检索出的记录集合临时保存到内存中,然后游标对这些保存在内存中的记录集合按顺序取出进行处理。
另外,在使用游标前需要理解指针这个概念。指针是确定当前记录的信息,可以理解为内存中保存记录的“地址”,在游标处理中,通过移动指针来进行逐行的数据处理。

例子1:
create procedure sp_cursor(out result text)
BEGIN
declare flag bit default 0;
declare tmp VARCHAR(20);
-- 申明游标
declare cur cursor for select distinct depart from employee;
-- 定义取出游标中所有记录时的处理
declare continue handler for not FOUND set flag = 1 ;
-- 打开游标
open cur;
while flag != 1 do
fetch cur into tmp;
if flag != 1 then 
set result = CONCAT_WS(",",result,tmp);-- 将多个字符串用","隔开
end if;
end while;
-- 关闭游标
CLOSE cur;
end

call sp_cursor(@r);
select @r ;

申明游标
declare 游标名 cursor for select 语句;

打开游标
open 游标名;
从指针中取得记录数据
fetch 游标名 into 变量名,...;

3. 数据导入导出
select * into outfile 'd:/out.csv' fields terminated by ',' from customer;
load data infile 'd:/out.csv' into table customer fields terminated by ',';
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql trigger