如何在MySQL中循环遍历表的所有行?
要循环遍历表的所有行,请在MySQL中使用存储过程。语法如下:
delimiter // CREATE PROCEDURE yourProcedureName() BEGIN DECLARE anyVariableName1 INT DEFAULT 0; DECLARE anyVariableName2 INT DEFAULT 0; SELECT COUNT(*) FROM yourTableName1 INTO anyVariableName1; SET anyVariableName2 =0; WHILE anyVariableName2 < anyVariableName1 DO INSERT INTO yourTableName2(yourColumnName,...N) SELECT (yourColumnName1,...N) FROM yourTableName1 LIMIT anyVariableName2,1; SET anyVariableName2 = anyVariableName2+1; END WHILE; End; //
为了理解上述语法,让我们创建两个表,一个表包含记录,第二个表将使用存储过程从循环中获取记录。
以下是创建第一个表的查询:
mysql> create table AllRows -> ( -> Id int, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.46 sec)
使用insert命令在第一个表中插入一些记录。查询如下:
mysql> insert into AllRows values(1,'John'); Query OK, 1 row affected (0.12 sec) mysql> insert into AllRows values(100,'Carol'); Query OK, 1 row affected (0.13 sec) mysql> insert into AllRows values(300,'Sam'); Query OK, 1 row affected (0.15 sec) mysql> insert into AllRows values(400,'Mike'); Query OK, 1 row affected (0.20 sec)
使用select语句显示表中的所有记录。查询如下:
mysql> select *from AllRows;
输出
+------+-------+ | Id | Name | +------+-------+ | 1 | John | | 100 | Carol | | 300 | Sam | | 400 | Mike | +------+-------+ 4 rows in set (0.00 sec)
以下是创建第二个表的查询:
mysql> create table SecondTableRows -> ( -> StudentId int, -> StudentName varchar(100) -> ); Query OK, 0 rows affected (0.54 sec)
现在您可以使用存储过程循环遍历表的所有行。存储过程如下:
mysql> delimiter // mysql> CREATE PROCEDURE Sp_AllRowsOfATable() -> BEGIN -> DECLARE lastRows INT DEFAULT 0; -> DECLARE startRows INT DEFAULT 0; -> SELECT COUNT(*) FROM AllRows INTO lastRows; -> SET startRows=0; -> WHILE startRows <lastRows DO -> INSERT INTO SecondTableRows(StudentId) SELECT (Id) FROM AllRows LIMIT startRows ,1; -> SET startRows= startRows+1; -> END WHILE; -> End; -> // Query OK, 0 rows affected (0.22 sec) mysql> delimiter ;
使用CALL命令调用存储过程。语法如下:
CALL yourStoredProcedureName;
调用上述存储过程以循环遍历第一个表的所有行。查询如下:
mysql> call Sp_AllRowsOfATable(); Query OK, 1 row affected (0.61 sec)
调用存储过程后,让我们检查第二个表发生了什么变化。查询如下:
mysql> select StudentId from SecondTableRows;
输出
+-----------+ | StudentId | +-----------+ | 1 | | 100 | | 300 | | 400 | +-----------+ 4 rows in set (0.00 sec)
广告