mysql里怎样循环遍历游标

--传入id,输出name和sex的存储过程,这里同个id有多条数据,所以需要用到游标。

DELIMITER //
CREATE PROCEDURE p5(IN v_id INT)
BEGIN
DECLARE nodata INT DEFAULT 0;#注意:这个变量声明必须放在游标声明前面
DECLARE v_name VARCHAR(30);
DECLARE v_sex CHAR(3);
DECLARE c_ns CURSOR FOR SELECT NAME,sex FROM t WHERE id = v_id;
DECLARE EXIT HANDLER FOR NOT FOUND SET nodata = 1;#当读到数据的最后一条时,设置变量为1
OPEN c_ns;
WHILE nodata = 0 DO#判断是不是到了最后一条数据
FETCH c_ns INTO v_name,v_sex;
SELECT v_name,v_sex,nodata;
END WHILE;  
CLOSE c_ns;
END
//

--执行该存储过程

mysql> call p5(2);

+--------+-------+--------+
| v_name | v_sex | nodata |
+--------+-------+--------+
| song   | 女    |      0 |
+--------+-------+--------+
1 row in set (0.04 sec)

+--------+-------+--------+
| v_name | v_sex | nodata |
+--------+-------+--------+
| dan    | 男    |      0 |
+--------+-------+--------+
1 row in set (0.05 sec)

Query OK, 0 rows affected, 1 warning (0.05 sec)


--注意:CONTINUE  会继续当前的block 中的语句, 它在set done=1 后继续执行下一个语句。EXIT  则在 set done=1 后离开当前的语句块

所以这里用了EXIT(黄色阴影部分).

如果是continue,结果如下:

mysql> call p5(2);
    -> //
+--------+-------+
| v_name | v_sex |
+--------+-------+
| song   | 女    |
+--------+-------+
1 row in set (0.00 sec)

+--------+-------+
| v_name | v_sex |
+--------+-------+
| dan    | 男    |
+--------+-------+
1 row in set (0.01 sec)

+--------+-------+
| v_name | v_sex |
+--------+-------+
| dan    | 男    |
+--------+-------+
1 row in set (0.02 sec)

Query OK, 0 rows affected, 1 warning (0.03 sec)


你可能感兴趣的:(MySql,学习,MySql,Developer)