创建一个 MySQL 存储过程,使用游标从表中获取行?

创建一个 MySQL 存储过程,使用游标从表中获取行?

以下是一个存储过程,它从具有以下数据的表“student_info”的名称列中获取记录 –

mysql> Select * from Student_info;
+-----+---------+------------+------------+
| id  | Name    | Address    | Subject    |
+-----+---------+------------+------------+
| 101 | YashPal | Amritsar   | History    |
| 105 | Gaurav  | Chandigarh | Literature |
| 125 | Raman   | Shimla     | Computers  |
| 127 | Ram     | Jhansi     | Computers  |
+-----+---------+------------+------------+
4 rows in set (0.00 sec)
mysql> Delimiter //
mysql> CREATE PROCEDURE cursor_defined(OUT val VARCHAR(20))
-> BEGIN
-> DECLARE a,b VARCHAR(20);
-> DECLARE cur_1 CURSOR for SELECT Name from student_info;
-> DECLARE CONTINUE HANDLER FOR NOT FOUND
-> SET b = 1;
-> OPEN CUR_1;
-> REPEAT
-> FETCH CUR_1 INTO a;
-> UNTIL b = 1
-> END REPEAT;
-> CLOSE CUR_1;
-> SET val = a;
-> END//
Query OK, 0 rows affected (0.04 sec)
mysql> Delimiter ;
mysql> Call cursor_defined2(@val);
Query OK, 0 rows affected (0.11 sec)
mysql> Select @val;
+------+
| @val |
+------+
| Ram |
+------+
1 row in set (0.00 sec)

从上面的结果集中,我们可以看到 val 参数的值是“Ram”,因为它是“Name”列的最后一个值。

原文来自:www.php.cn
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容