您的位置:首页 > 数据库 > MySQL

MySQL Study之--MySQL存储过程循环

2015-08-04 14:33 639 查看
MySQL Study之--MySQL存储过程循环

在MySQL存储过程的语句中有三个标准的循环方式:WHILE循环,LOOP循环以及REPEAT循环。还有一种非标准的循环方式:GOTO,不过这种循环方式最好别用,很容易引起程序的混乱,在这里就不错具体介绍了。

这几个循环语句的格式如下:

WHILE……DO……END WHILE

REPEAT……UNTIL END REPEAT

LOOP……END LOOP

GOTO。


案例分析:

mysql> select * from t2;

+------+-------+

| id | name |

+------+-------+

| 10 | tom |

| 20 | jerry |

| 30 | rose |

+------+-------+

3 rows in set (0.00 sec)

mysql> insert into t2 values (40,concat('usr',10)) ;

Query OK, 1 row affected (0.06 sec)

mysql> select * from t2;

+------+-------+

| id | name |

+------+-------+

| 10 | tom |

| 20 | jerry |

| 30 | rose |

| 40 | usr10 |

+------+-------+

4 rows in set (0.00 sec)

1、while 循环:

mysql> delimiter //

mysql> create procedure proc01()

-> begin

-> declare i int;

-> set i=0;

-> while i<6 do

-> insert into t2 values (i,concat('usr',i));

-> set i=i+1;

-> end while ;

-> end;

-> //

-----如果没有初始化,i默认变量值为NULL,而NULL和任何值操作的结果都是NULL。

mysql> delimiter ;


执行存储过程:
mysql> call proc01();

验证:

mysql> select * from t2;

+------+-------+

| id | name |

+------+-------+

| 10 | tom |

| 20 | jerry |

| 30 | rose |

| 40 | usr10 |

| 0 | usr0 |

| 1 | usr1 |

| 2 | usr2 |

| 3 | usr3 |

| 4 | usr4 |

| 5 | usr5 |

+------+-------+

10 rows in set (0.01 sec)

2、repeat 循环:

mysql> delimiter //

mysql> create procedure proc02()

-> begin

-> declare i int default 0 ;

-> repeat

-> insert into t3 values (i,concat('usr',i));

-> set i=i+1;

-> until i>=5

-> end repeat;

-> end;

-> //

Query OK, 0 rows affected (0.01 sec)

mysql> delimiter ;

执行存储过程:



mysql> call proc02();

Query OK, 1 row affected (0.07 sec)

验证:

mysql> select * from t3;

+----+------+

| id | name |

+----+------+

| 0 | usr0 |

| 1 | usr1 |

| 2 | usr2 |

| 3 | usr3 |

| 4 | usr4 |

+----+------+

5 rows in set (0.00 sec)

3、loop 循环:

mysql> delimiter //

mysql> create procedure proc03()

-> begin

-> declare i int default 6;

-> loop_label:loop

-> insert into t2 values (i,concat('usr',i));

-> set i=i+1;

-> if i>=9 then

-> leave loop_label;

-> end if;

-> end loop;

-> end;

-> //

Query OK, 0 rows affected (0.01 sec)

mysql> delimiter ;


-----从上面这个例子可以看出,使用LOOP编写同样的循环控制语句要比使用while和repeat编写的要复杂一些:在循环内部加入了IF……END
IF语句,在IF语句中又加入了LEAVE语句,LEAVE语句的意思是离开循环,LEAVE的格式是:LEAVE 循环标号。

执行存储过程:

mysql> call proc03;

Query OK, 1 row affected (0.02 sec)

验证:

mysql> select * from t2;

+------+-------+

| id | name |

+------+-------+

| 10 | tom |

| 20 | jerry |

| 30 | rose |

| 40 | usr10 |

| 0 | usr0 |

| 1 | usr1 |

| 2 | usr2 |

| 3 | usr3 |

| 4 | usr4 |

| 5 | usr5 |

| 6 | usr6 |

| 7 | usr7 |

| 8 | usr8 |

+------+-------+

13 rows in set (0.00 sec)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: