该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
利用游标查询记录, 怎么多一条记录呢??=================
BEGIN
#Routine body goes here...
DECLARE done BOOLEAN DEFAULT 0;
DECLARE o INT;
# 定义游标
DECLARE ordernumbers CURSOR
FOR
SELECT order_num FROM orders ORDER BY order_num;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
#CREATE TABLE IF NOT EXISTS test_table(order_num int);
OPEN ordernumbers;
REPEAT
FETCH ordernumbers INTO o;
select o;
#INSERT INTO test_table(order_num) VALUES (o);
UNTIL done END REPEAT;
CLOSE ordernumbers;
END
出现了,多一个条记录的问题;mysql> call processorders();
+-------+
| o |
+-------+
| 20005 |
+-------+
1 row in set (0.00 sec)
+-------+
| o |
+-------+
| 20006 |
+-------+
1 row in set (0.00 sec)
+-------+
| o |
+-------+
| 20007 |
+-------+
1 row in set (0.00 sec)
+-------+
| o |
+-------+
| 20008 |
+-------+
1 row in set (0.00 sec)
+-------+
| o |
+-------+
| 20009 |
+-------+
1 row in set (0.00 sec)
+-------+
| o |
+-------+
| 20009 |
+-------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
==================
分析:(其他类似的问题,copy过来的)
repeat
/*游标向下走一步*/
FETCH cur1 INTO o;
select o;
until done end repeat;
你可以设想一下最后一条记录时。 把值赋给 o, 你的程序 select o 输出,此刻 done 为0 ,
然后执行 repeat, 再执行 FETCH cur1 INTO o; 此时,已经没有记录,导致 done 为 1, o中的值仍是上次的值没有更新。 再执行 select o; 输出仍为上次的 o值。 until done end repeat; done 已被置为1,退出循环。
=========解决方法:=========加一个判断就好了。
repeat
FETCH cur1 INTO o;
if not done then
select o;
end if;
until done end repeat;