• 注册
当前位置:1313e > 数据库 >正文

mysql基于游标_基于MySQL游标的具体使用详解

测试表 level ;

create table test.level (name varchar(20));

再 insert 些数据 ;

代码

初始化

drop procedure if exists usecursor //

建立 存储过程 create

create procedure usecursor()

begin

局部变量的定义 declare

declare tmpname varchar(20) default '' ;

declare allname varchar(255) default '' ;

declare cur1 cursor for select name from test.level ;

mysql 游标 异常后 捕捉

并设置 循环使用 变量 tmpname 为 null 跳出循环。

declare continue handler for sqlstate '02000' set tmpname = null;

开游标

open cur1;

游标向下走一步

fetch cur1 into tmpname;

循环体 这很明显 把mysql 游标查询出的 name 都加起并用 ; 号隔开

while ( tmpname is not null) do

set tmpname = concat(tmpname ,";") ;

set allname = concat(allname ,tmpname) ;

游标向下走一步

fetch cur1 into tmpname;

结束循环体:

end while;

关闭游标

close cur1;

选择数据

select allname ;

结束存储过程

end;//

调用存储过程:

call usecursor()//

运行结果:

mysql> call usecursor()//

+--------------------------------------+

| allname                              |

+--------------------------------------+

| f1;c3;c6;c5;c2;c4;c1;f1;f3;f4;f2;f5; |

+--------------------------------------+

1 row in set (0.00 sec)

loop循环游标:

delimiter $$

drop procedure if exits cursor_example$$

create procedure cursor_example()

reads sql data

begin

declare l_employee_id int;

declare l_salary numeric(8,2);

declare l_department_id int;

declare done int default 0;

declare cur1 cursor for select employee_id, salary, department_id from employees;

declare continue handler for not found set done=1;

open cur1;

emp_loop: loop

fetch cur1 into l_employee_id, l_salary, l_department_id;

if done=1 then

leave emp_loop;

end if;

end loop emp_loop;

close cur1;

end$$

delimiter ;

repeat循环游标:

/*创建过程*/

delimiter //

drop procedure if exists test //

create procedure test()

begin

declare done int default 0;

declare a varchar(200) default '';

declare c varchar(200) default '';

declare mycursor cursor for select  fusername from uchome_friend;

declare continue handler for not found set done=1;

open mycursor;

repeat

fetch mycursor into a;

if not done then

set c=concat(c,a);/*字符串相加*/

end if;

until done end repeat;

close mycursor;

select c;

end //

delimiter ;

/*创建过程*/

delimiter //

drop procedure if exists test //

create procedure test()

begin

declare done int default 0;

declare a varchar(200) default '';

declare c varchar(200) default '';

declare mycursor cursor for select  fusername from uchome_friend;

declare continue handler for not found set done=1;

open mycursor;

repeat

fetch mycursor into a;

if not done then

set c=concat(c,a);/*字符串相加*/

end if;

until done end repeat;

close mycursor;

select c;

end //

delimiter ;

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录