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==============