您的当前位置:首页正文

mysql数据库中关于Cursor游标的使用方法_MySQL

2020-11-09 来源:爱站旅游

========
游标的Handler

mysql> DELIMITER //
mysql> CREATE FUNCTION city_list() RETURNS VARCHAR(255)
-> BEGIN
->
-> DECLARE finished INTEGER DEFAULT 0;
-> DECLARE city_name VARCHAR(50) DEFAULT "";
-> DECLARE list VARCHAR(255) DEFAULT "";
-> DECLARE city_cur CURSOR FOR SELECT city FROM employee;
-> DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
->
-> OPEN city_cur;
->
-> get_city: LOOP
-> FETCH city_cur INTO city_name;
-> IF finished THEN
-> LEAVE get_city;
-> END IF;
-> SET list = CONCAT(list,", ",city_name);
-> END LOOP get_city;
->
-> CLOSE city_cur;
->
-> RETURN SUBSTR(list,3);
-> END
-> //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;
mysql>
mysql> SELECT city_list() AS cities;
+------------------------------------------------------------------------------------+
| cities |
+------------------------------------------------------------------------------------+
| Toronto, Vancouver, Vancouver, Vancouver, Vancouver, New York, New York, Vancouver |
+------------------------------------------------------------------------------------+
1 row in set (0.02 sec)

mysql>
mysql> drop function city_list;
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql>
mysql>
mysql> drop table Employee;
Query OK, 0 rows affected (0.00 sec)
====


mysql 游标数据输出实例

mysql> delimiter $$
mysql> CREATE PROCEDURE myProc()
-> READS SQL DATA
-> BEGIN
-> DECLARE l_last_row INT DEFAULT 0;
-> DECLARE l_dept_id INT;
-> DECLARE c_dept CURSOR FOR
-> SELECT id
-> FROM employee;
-> /* handler to set l_last_row=1 if a cursor returns no more rows */
-> DECLARE continue handler for NOT FOUND SET l_last_row=1;
->
-> OPEN c_dept;
-> dept_cursor: LOOP
-> FETCH c_dept INTO l_dept_id;
-> IF (l_last_row=1) THEN
-> LEAVE dept_cursor;
-> END IF;
-> select l_dept_id;
->
-> END LOOP dept_cursor;
-> CLOSE c_dept;
->
-> END$$
Query OK, 0 rows affected (0.01 sec)

mysql>
mysql> delimiter ;

显示全文