標籤: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語句向資料表中批量插入資料