Create a MySQL stored procedure which fetches the rows from a table by using a cursor?

MySQLMySQLi Database

Following is a stored procedure which fetches the records from name column of table ‘student_info’ having 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)

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

raja
Published on 21-Feb-2018 11:19:45
Advertisements