例子来自《深入浅出Mysql》第二版 12.2.7 流程控制
向 table actor 中 insert
数据。
- 创建 table
actor
create table actor(first_name varchar(256), second_name varchar(256));
- 定义存储过程
mysql> delimiter $$ # 把结束符从分号 ; 变成 $$ ,避免存储过程中的分号被识别成了结束
mysql> CREATE PROCEDURE actor_insert()
-> BEGIN
-> set @x = 0;
-> INS: LOOP # 开始循环
-> INSERT INTO actor(first_name, second_name) VALUES ('Test', '201');
-> set @x = @x + 1;
-> IF @x = 100 THEN
-> LEAVE INS; # 跳出循环
-> END IF;
-> END LOOP INS; # 定义循环结束
-> END;
-> $$ # 存储过程的定义结束
Query OK, 0 rows affected (0.07 sec)
mysql> delimiter ; # 把结束符恢复为分号 ;
- 调用存储过程
mysql> call actor_insert(); # 调用存储过程
Query OK, 0 rows affected (1.11 sec)
mysql> select count(*) from actor;
+----------+
| count(*) |
+----------+
| 100 |
+----------+
1 row in set (0.00 sec)
- 查看一下存储过程中定义的变量
x
mysql> select @x;
+------+
| @x |
+------+
| 100 |
+------+
1 row in set (0.00 sec)