在游标循环中调用存储过程,而不跳过继续处理程序

时间:2012-05-16 17:27:08

标签: mysql stored-procedures cursor handler

我试图在Cursor的循环中调用MySQL中的存储过程。在循环中执行INSERT时,游标行为正常;但是如果我尝试调用存储过程,则继续处理程序'设置done = 1'并在处理完第一条记录后提前退出循环。有关如何解决这个问题的任何想法?感谢。

declare test_cursor cursor for 
       select projectid, projectdesc
         from tblProjects
        order by projectdesc;          

DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

set done = 0;  
open test_cursor;

repeat

  fetch test_cursor into wprojectid, wprojectdesc;

  if not done then  

    insert into tblTest (a, b) values (wprojectid, wprojectdesc);   <--this would work
    call spTest(wprojectid, wprojectdesc, @retrn);                                    <--this trips the Handler after first loop

  end if;      

until done end repeat;

close test_cursor; 

2 个答案:

答案 0 :(得分:2)

我不确定,但是试着看看这段代码是否有效?

declare test_cursor cursor for 
       select projectid, projectdesc
         from tblProjects
        order by projectdesc;          

DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
DECLARE done_holder INT;


set done = 0;
open test_cursor;

repeat

  fetch trade_cursor into wprojectid, wprojectdesc;

  if not done then  

    set done_holder = done;
    insert into tblTest (a, b) values wprojectid, wprojectdesc;
    call spTest(a, b, @retrn);
    set done = done_holder;

  end if;      

until done end repeat;

close test_cursor; 

答案 1 :(得分:0)

我认为问题出在这里 - '调用spTest(a,b,@ retrn);',尝试用这个改变它 -

CALL spTest(wprojectid, wprojectdesc, @retrn);

所以,你的代码可以是这样的 -

  DECLARE done INT DEFAULT 0;
  DECLARE wprojectid, wprojectdesc  INT;
  DECLARE test_cursor CURSOR FOR SELECT projectid, projectdesc FROM tblProjects ORDER BY projectdesc;
  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

  SET done = 0;
  OPEN test_cursor;

  REPEAT
  FETCH test_cursor INTO wprojectid, wprojectdesc;
    IF NOT done THEN
      INSERT INTO tblTest (a, b) VALUES (wprojectid, wprojectdesc);
      CALL spTest(wprojectid, wprojectdesc, @retrn);
    END IF;
  UNTIL done
  END REPEAT;
  CLOSE test_cursor;