MySQL Cursorカーソルのストレージ中の使用
2533 ワード
MySQL Cursorカーソルのストレージ中の使用
カーソルの役割は、クエリー・データベースから返されるレコードを巡回して、対応する操作を行うことです.
declares a cursor and associates it with a SELECT statement that retrieves the rows to be traversed by the cursor.
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 table Read only: Not updatable Nonscrollable: Can be traversed only in one direction and cannot skip rows
新しいテーブル
新しいストアド・プロシージャを作成し、ストアド・プロシージャでカーソルを使用してデータセットを巡回し、次のようにデータを操作します.
コードを使用すると、ストレージ中にカーソルを介してデータセットの遍歴が表示されます.
以上のストレージ・プロシージャはmysqlカーソルの構文に関連しています.次を参照してください.
http://dev.mysql.com/doc/refman/5.6/en/cursors.html
==============END==============
カーソルの役割は、クエリー・データベースから返されるレコードを巡回して、対応する操作を行うことです.
declares a cursor and associates it with a SELECT statement that retrieves the rows to be traversed by the cursor.
MySQL supports cursors inside stored programs. The syntax is as in embedded SQL. Cursors have these properties:
新しいテーブル
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)
);
新しいストアド・プロシージャを作成し、ストアド・プロシージャでカーソルを使用してデータセットを巡回し、次のようにデータを操作します.
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>
コードを使用すると、ストレージ中にカーソルを介してデータセットの遍歴が表示されます.
以上のストレージ・プロシージャはmysqlカーソルの構文に関連しています.次を参照してください.
http://dev.mysql.com/doc/refman/5.6/en/cursors.html
==============END==============