MySQL 使用while語句向資料表中批量插入資料

來源:互聯網
上載者:User

標籤:cte   creat   while迴圈   proc   mysq   bsp   end   中文意思   from   

 

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)

 

MySQL 使用while語句向資料表中批量插入資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.