不知道 MySQL 有没有类似 PostgreSQL 的 generate_series () 函数,在生成测试数据时非常方便,不需要编写存储过程。这里记录下通过存储过程批量插入数据。
创建测试表
1 2 3 4 5 6 7 8 9 10 11
francs@localhost:francs>create table test_1(id int4 primary key, name ichar(32)); Query OK, 0 rows affected (0.16 sec) francs@localhost:francs>desc test_1; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | ichar(32) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 2 rows inset (0.00 sec)
批量插入数据存储过程
1 2 3 4 5 6 7 8 9 10 11 12 13
DELIMITER // CREATEPROCEDUREpro_insert() BEGIN DECLAREiINT; SET i = 0; WHILE i <= 10000DO insert into test_1(id, name ) values(i,CONCAT(ID,'_a')); SET i = i + 1; ENDWHILE; END // DELIMITER ;
创建存储过程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
francs@localhost:francs>DELIMITER // francs@localhost:francs>CREATE PROCEDURE pro_insert() -> BEGIN -> DECLARE i INT; ->SET i = 0; -> ->WHILE i <= 10000 DO ->insert into test_1(id, name ) values(i,CONCAT(ID,'_a')); ->SET i = i + 1; -> END WHILE; -> END -> // DELIMITER ; Query OK, 0 rows affected (0.07 sec) francs@localhost:francs> DELIMITER ;