您好,欢迎访问一九零五行业门户网

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

bitscn.com
测试表 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 ;
bitscn.com
其它类似信息

推荐信息