简体   繁体   English

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

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

I am reading an article on stored procedures and this is the code: 我正在阅读有关存储过程的文章,这是代码:

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 ;

I am using a simple database named "mydatabase". 我正在使用一个名为“mydatabase”的简单数据库。 After running the above code it gives me this error: ERROR 1338 (42000): Cursor declaration after handler declaration What is wrong and how can I fix it? 运行上面的代码后,它给了我这个错误: ERROR 1338 (42000): Cursor declaration after handler declaration什么问题,我该如何解决?

This is my first time working with stored procedures. 这是我第一次使用存储过程。

Per MySql docs : 每个MySql 文档

Cursor declarations must appear before handler declarations and after variable and condition declarations. 游标声明必须出现在处理程序声明之前以及变量和条件声明之后。

So I updated the code as follows: 所以我更新了代码如下:

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 ;

And now works fine. 现在工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM