MySql 存储过程错误 [ERROR 1338 (42000): 处理程序声明后的游标声明]

MySql stored procedure error [ERROR 1338 (42000): Cursor declaration after handler declaration]

我正在阅读一篇关于存储过程的文章,这是代码:

delimiter //

create procedure largest_order(out largest_id int) 
begin
  declare this_id int;
  declare this_amount float;
  declare l_amount float default 0.0;
  declare l_id int;

  declare done int default 0;
  declare continue handler for sqlstate '02000' set done = 1;
  declare c1 cursor for select orderid, amount from orders;

  open c1;
  repeat
    fetch c1 into this_id, this_amount;
    if not done then
      if this_amount > l_amount then
        set l_amount=this_amount;
        set l_id=this_id;
      end if;
    end if;
   until done end repeat; 
  close c1;

  set largest_id=l_id;

end
//

delimiter ;

我正在使用一个名为 "mydatabase" 的简单数据库。在 运行 上面的代码之后它给了我这个错误:ERROR 1338 (42000): Cursor declaration after handler declaration 出了什么问题,我该如何解决?

这是我第一次使用存储过程。

根据 MySql docs:

Cursor declarations must appear before handler declarations and after variable and condition declarations.

所以我更新了代码如下:

delimiter //

create procedure largest_order(out largest_id int) 
begin
  declare this_id int;
  declare this_amount float;
  declare l_amount float default 0.0;
  declare l_id int;

  -- 1. cursor finished/done variable comes first
  declare done int default 0;
  -- 2. the curser declaration and select
  declare c1 cursor for select orderid, amount from orders;
  -- 3. the continue handler is defined last
  declare continue handler for sqlstate '02000' set done = 1;


  open c1;
  repeat
    fetch c1 into this_id, this_amount;
    if not done then
      if this_amount > l_amount then
        set l_amount=this_amount;
        set l_id=this_id;
      end if;
    end if;
   until done end repeat; 
  close c1;

  set largest_id=l_id;

end
//

delimiter ;

现在工作正常。