Calling a Stored Procedure Within a Cursor Loop, Without Tripping the Continue Handler

人走茶凉 提交于 2019-12-11 04:04:22

问题


I am trying to call a Stored Procedure in MySQL within the loop of a Cursor. The cursor behaves properly when doing an INSERT in the loop; but if I try to call a Stored Procedure, the continue Handler 'sets done = 1' and will exit the loop prematurely, after the first record is processed. Any thoughts on how to work around this? Thanks.

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; 

回答1:


I'm NOT sure about it, but try to see if this code works or not ?

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; 



回答2:


I think the problem is here - 'call spTest(a, b, @retrn);', try to change it with this one -

CALL spTest(wprojectid, wprojectdesc, @retrn);

so, your code can be like this -

  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;


来源:https://stackoverflow.com/questions/10623588/calling-a-stored-procedure-within-a-cursor-loop-without-tripping-the-continue-h

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!