MySQL 使用while語句向數據表中批量插入數據


 

1.創建一張數據表

mysql> create table test_while (
    ->   id int primary key) charset = utf8;
Query OK, 0 rows affected (0.28 sec)

  查看數據表的結構

 

mysql> desc test_while;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.01 sec)

2.創建存儲過程,在begin..end里面寫while循環以及insert語句

mysql> delimiter #
mysql> create procedure test_two()
    -> begin
    ->     declare i int default 0;
    ->     while i < 10 do
    ->         insert into test_while(id) values(i);
    ->         set i = i + 1;
    ->     end while;
    -> end #
Query OK, 0 rows affected (0.00 sec)

   注釋:(1)delimiter 中文意思定界符,分隔符,   在MySQL中用來設置語句的結束符。MySQL的默認結束符是 ; 設置 delimiter # 之后begin..end中以分號結束的代碼

          塊就不會執行啦, 然后在end后面加#結束符結束。 在創建完存儲過程后用delimiter ; 恢復默認設置

           (2)declare 定義一個變量  declare int i default 0;   定義一個初始值為0的整型變量

 

3.調用存儲過程

mysql> delimiter ;
mysql> call test_two();
Query OK, 1 row affected (0.35 sec)

4.查看存儲過程中的代碼塊是否調用成功了

mysql> select * from test_while;
+----+
| id |
+----+
|  0 |
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
|  9 |
+----+
10 rows in set (0.00 sec)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM