Home > Database > Mysql Tutorial > Create a MySQL stored procedure to get rows from a table using a cursor?

Create a MySQL stored procedure to get rows from a table using a cursor?

WBOY
Release: 2023-09-16 21:45:07
forward
1199 people have browsed it

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

The following is a stored procedure that gets the records from the name column of the table "student_info" which has the following data -

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)
Copy after login

From the above result set , we can see that the value of the val parameter is "Ram" because it is the last value of the "Name" column.

The above is the detailed content of Create a MySQL stored procedure to get rows from a table using a cursor?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template