学习mysql存储过程,并且用到游标

定义一个存储过程,用到游标,从一个表中取值,插入到另外一个表中。
drop procedure if exists search_test;
create procedure search_test(in id int,out out_min_id varchar(200))
begin
declare finished boolean default 0 ;
declare tmp varchar(200) ;
declare s_test cursor for select r_id from A where n_code=id;  //定义游标
declare continue handler for sqlstate '02000' set finished=1;   //定义结束标志
open s_test;           //打开游标
repeat             //循环
FETCH s_test into tmp;
if not finished then
set out_min_id=tmp;
insert into B(n_code) values(out_min_id);
end if;
until finished end repeat;
close s_test;         //关闭游标
select out_min_id;
end

mysql打印变量值用select 变量名的方式;

用LOOP实现循环方式

drop procedure if exists search_test;
create procedure search_test(in id int,out out_min_id varchar(200))

begin

declare finished boolean default 0 ;
declare tmp varchar(200) ;
declare s_test cursor for select rf_id from urm_ipqam_frequency where network_code=id;
declare continue handler for sqlstate '02000' set finished=1;
open s_test;
myloop:LOOP
FETCH s_test into tmp;
if finished then
leave myloop;
end if;
set out_min_id=tmp;
insert into urm_network_area_his(network_code) values(out_min_id);
end loop myloop;
close s_test;
select out_min_id;
end

 

posted on 2014-05-13 15:59  leizi1987  阅读(179)  评论(0编辑  收藏  举报