一、表
学生表
create table `t_student` (
`stunum` int(11) not null auto_increment,
`stuname` varchar(20) default null,
`birthday` date default null,
primary key (`stunum`)
) engine=innodb default charset=utf8
学生分数表
create table `t_stu_score` (
`id` int(11) not null auto_increment,
`stunum` int(11) default null,
`score` decimal(6,2) default null,
primary key (`id`),
key `fk_t_stu_score` (`stunum`),
constraint `fk_t_stu_score` foreign key (`stunum`) references `t_student` (`stunum`)
学生详细表
create table `t_stu_detail` (
primary key (`id`)
将t_student和t_stu_score表中满足一定条件的数据插入到t_stu_detail中。
二、过程
delimiter &&
create procedure proc_addstudetail( in p_score decimal(6,2) )
begin
declare vstunum int;
declare vstuname varchar(20);
declare vbirthday date;
declare vscore decimal(6,2);
declare done int;
-- 定义游标
declare stucursor cursor
for
select stunum,stuname,birthday from t_student;
-- 定义结束标记
declare continue handler for not found set done = 1;
-- 打开游标
open stucursor;
-- 循环
stuloop:loop
-- 取游标中的数据
fetch stucursor into vstunum,vstuname,vbirthday;
if done = 1 then
leave stuloop;
end if;
if date(vbirthday) >= '1990-03-01' then
select score into vscore from t_stu_score where stunum = vstunum;
if vscore >= p_score then
insert into t_stu_detail values(null,vstunum,vscore);
end loop stuloop;
-- 关闭游标
close stucursor;
end
&&
delimiter ;
三、调用过程
call proc_addstudetail(86);