我們可以使用遊標來處理預存程序中的結果集。基本上,遊標允許我們迭代查詢返回的一組行並相應地處理每一行。
為了示範CURSOR 在MySQL 預存程序中的使用,我們正在建立以下預存程序,該過程基於名為「student_info」的表的值,如下所示-
mysql> Select * from student_info; +-----+---------+----------+------------+ | id | Name | Address | Subject | +-----+---------+----------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Jaipur | Literature | | 125 | Raman | Shimla | Computers | +-----+---------+----------+------------+ 3 rows in set (0.00 sec)
以下查詢將建立一個名為「list_address」的過程,該過程返回表中儲存的所有位址的清單-
mysql> Delimiter // mysql> CREATE PROCEDURE list_address (INOUT address_list varchar(255)) -> BEGIN -> DECLARE value_finished INTEGER DEFAULT 0; -> DECLARE value_address varchar(100) DEFAULT ""; -> DEClARE address_cursor CURSOR FOR -> SELECT address FROM student_info; -> DECLARE CONTINUE HANDLER -> FOR NOT FOUND SET value_finished = 1; -> OPEN address_cursor; -> get_address: LOOP -> FETCH address_cursor INTO value_address; -> IF value_finished = 1 THEN -> LEAVE get_address; -> END IF; -> SET address_list = CONCAT(value_address,";",address_list); -> END LOOP get_address; -> CLOSE address_cursor; -> END // Query OK, 0 rows affected (0.00 sec)
現在,當我們呼叫這個過程時,我們可以看到下面的結果-
mysql> DELIMITER ; mysql> Set @address_list = ""; Query OK, 0 rows affected (0.00 sec) mysql> CALL list_address(@address_list); Query OK, 0 rows affected (0.00 sec) mysql> Select @address_list; +-------------------------+ | @address_list | +-------------------------+ | Shimla;Jaipur;Amritsar; | +-------------------------+ 1 row in set (0.00 sec)
以上是我們如何在 MySQL 預存程序中處理結果集?的詳細內容。更多資訊請關注PHP中文網其他相關文章!