嗨,我有以下存储过程
DROP PROCEDURE IF EXISTS `p25`$$
CREATE DEFINER=`root`@`%` PROCEDURE `p25`()
BEGIN
DECLARE b BOOLEAN;
DECLARE a VARCHAR(10);
DECLARE cur_1 CURSOR FOR SELECT t FROM sample_table;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET b = TRUE;
OPEN cur_1;
lbl:LOOP
IF b = TRUE THEN
LEAVE lbl;
END IF;
IF NOT b= TRUE THEN
FETCH cur_1 INTO a;
END IF;
END LOOP;
CLOSE cur_1;
END$$
select 语句实际上返回 5 行 但上述过程在获取一行后不会循环遍历其他行。 并且 b 值永远不会设置为 true,因此它将进入无限循环。 我的代码有什么问题吗? 请有人帮助我..
我找到了解决方案,感谢您的帮助。 我认为我检查值的方式是错误的。 所以现在,我想根据获取的行值从其他表中获取值。我怎样才能打印结果 ||当前行值|| 从其他表获取的值|| 作为获取所有行的结果。
原因之一可能是您可能再次在游标内使用了 select into 语句,这会将游标循环内的那些嵌套 select 语句的处理程序值设置为 1。您可以在内部使用 select 语句后将处理程序值重置为 0,并将处理程序条件移至 FETCH 命令旁边。 示例:
...
BEGIN
DECLARE cursor_finished INTEGER DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET cursor_finished = 1;
...
open table_cursor;
get_row: LOOP
FETCH table_cursor INTO v_variable1, v_variable3;
IF cursor_finished = 1 THEN
LEAVE get_row;
END IF;
....
Select id into v_id from sometable; -- this sets cursor_finished to 1.
SET cursor_finished = 0; -- hence reset this value for cursor.
....
END
尝试改变-
IF NOT b= TRUE THEN
FETCH cur_1 INTO a;
与-
IF b IS NULL THEN
FETCH cur_1 INTO a;
试试这个代码 -
DECLARE b INT DEFAULT 0;
DECLARE a VARCHAR(10);
DECLARE cur_1 CURSOR FOR SELECT t FROM sample_table;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1;
OPEN cur_1;
REPEAT
FETCH cur_1 INTO a;
IF NOT b THEN
-- do something:
...
...
...
END IF;
UNTIL b END REPEAT;
CLOSE cur_1;
结构应该类似于以下代码的位置很重要:“SET v_finished = FALSE;”
DECLARE v_finished BOOLEAN;
DECLARE cur_1 CURSOR FOR SELECT col_1, col_2 FROM sample_table;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = TRUE;
OPEN cur_1;
lbl_loop_for_cur_1: LOOP
SET v_finished = FALSE;
FETCH cur_1 INTO v_col_1, v_col_2;
IF v_finished = TRUE THEN
LEAVE lbl_loop_for_cur_1;
END IF;
-- <your other queries for loop body>
END LOOP;
CLOSE cur_1;
强调一下,“navneet kr verma”说,我们需要
如果完成了
==>
如果完成= 1 那么