MySQL Cursor在存储过程当中的使用html
游标的做用就是用于对查询数据库所返回的记录进行遍历,以便进行相应的操做。mysql
declares a cursor and associates it with a SELECT statement that retrieves the rows to be traversed by the cursor.sql
MySQL supports cursors inside stored programs. The syntax is as in embedded SQL. Cursors have these properties:数据库
Asensitive: The server may or may not make a copy of its result tableide
Read only: Not updatableoop
Nonscrollable: Can be traversed only in one direction and cannot skip rowsspa
新建如下表code
create table t3( id int not null, num_t int not null, primary key (id) ); create table t4( id int not null, num_tt int not null, primary key (id) ); insert into t3 (id,num_t) values(1,2),(3,4),(5,6),(6,2),(7,4),(8,6); insert into t4 (id,num_tt) values(1,2),(3,4),(5,6),(9,2),(12,4),(76,6); create table t5( id int not null, num_ttt int not null, primary key (id) );
新建一个存储过程,并在存储过程当中使用游标对数据集进行遍历,并操做数据,以下:server
mysql> DELIMITER // mysql> mysql> CREATE PROCEDURE curdemo() -> BEGIN -> DECLARE done INT DEFAULT FALSE; -> DECLARE a, b, c INT; -> DECLARE cur1 CURSOR FOR SELECT id,num_t FROM test.t3; -> DECLARE cur2 CURSOR FOR SELECT num_tt FROM test.t4; -> DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; -> -> OPEN cur1; -> OPEN cur2; -> -> read_loop: LOOP -> FETCH cur1 INTO a, b; -> FETCH cur2 INTO c; -> IF done THEN -> LEAVE read_loop; -> END IF; -> IF b < c THEN -> INSERT INTO test.t5(id,num_ttt) VALUES (a,b); -> ELSE -> INSERT INTO test.t5(id,num_ttt) VALUES (a,c); -> END IF; -> END LOOP; -> -> CLOSE cur1; -> CLOSE cur2; -> END -> // Query OK, 0 rows affected (0.00 sec) mysql> mysql> DELIMITER ; mysql> CALL curdemo(); Query OK, 0 rows affected (0.55 sec) mysql> select * from t5; +----+---------+ | id | num_ttt | +----+---------+ | 1 | 2 | | 3 | 4 | | 5 | 6 | | 6 | 2 | | 7 | 4 | | 8 | 6 | +----+---------+ 6 rows in set (0.06 sec) mysql>
经过代码,你能够看到在存储过程当中经过游标进行数据集的遍历。htm
以上的存储过程涉及到mysql游标的语法,请看:
http://dev.mysql.com/doc/refman/5.6/en/cursors.html
==============END==============