如何在mysql中使用游标循环结束循环

时间:2018-02-17 10:46:49

标签: mysql database

以下代码用于从名为employee7的表中查找前五个最高薪员工,并使用mysql中的游标将详细信息添加到另一个名为temp的表中,但是我收到了错误

  

你的mysql语法有错误,请检查与mysql服务器版本相对应的mannual,以便在#g; loop cursorloop附近使用正确的语法;    关闭c7;   结束;在第17行

DELIMITER //
create procedure cursordemo()
begin 
    declare eno int(8);
    declare ename varchar(15);
    declare esal int(10);
    declare c7 cursor for select empno,empnm,empsal from employee7 order by empsal desc;
    open c7;
    cursorloop:loop
    fetch c7 into eno,ename,esal;
    if c7.rowcount>5 then  
        leave cursorloop;
    insert into temp values (esal,eno,ename);
    end loop cursorloop;
    close c7;
    end //
delimiter ;

1 个答案:

答案 0 :(得分:0)

我不知道你在哪里有使用c7.rowcount的想法,但是这不是有效的mysql在mysql中退出游标循环的更常用的方法是使用一个处理程序来自示例

DELIMITER //
create procedure cursordemo()
begin 
    declare eno int(8);
    declare ename varchar(15);
    declare esal int(10);
    declare done int default 0;
    declare c7 cursor for select emp_no,last_name,salary from employees order by salary desc;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    open c7;
    cursorloop:loop
    if done = true then  
        leave cursorloop;
    end if;
    fetch c7 into eno,ename,esal;

    insert into temp values (esal,eno,ename);
    end loop cursorloop;
    close c7;
    end //
delimiter ;