mysql存储过程中的循环语句有三种:1、while循环语句,语法“while 条件表达式 do 循环语句 end while”;2、repeat循环语句,语法“repeat 循环语句 until 条件表达式 end repeat”;3、loop循环语句,语法“[begin_label:] loop 条件和循环语句列表 end loop [end_label]”。
本教程操作环境:windows7系统、mysql8版本、dell g3电脑。
mysql提供了循环语句,允许您根据条件重复执行一段sql代码。有三种循环语句在mysql: while,repeat 和loop。
while循环
while语句的语法如下:
while expression do statementsend while
while 循环检查expression在每次迭代的开始。如果expression评估为true,mysql将 在评估statements之间执行 while,end while直到expression评估为止false。while 循环称为预测试循环,因为它在statements 执行之前检查表达式。
以下流程图说明了while循环语句:
以下是while 在存储过程中使用循环语句的示例:
delimiter $$drop procedure if exists test_mysql_while_loop$$ create procedure test_mysql_while_loop ( ) begin declare x int; declare str varchar ( 255 ); set x = 1; set str = ''; while x <= 5 do set str = concat( str, x, ',' ); set x = x + 1; end while; select str;end $$delimiter ;
在test_mysql_while_loop上面的存储过程中:
首先,我们str 重复构建字符串,直到x 变量的值 大于5。
然后,我们使用select语句显示最终字符串。
请注意,如果我们不初始化 x变量,则其默认值为null。因此,while循环语句中的条件始终是true 并且您将具有无限循环,这不是期望的。
我们来测试一下test_mysql_while_loop存储过程:
call test_mysql_while_loop();
输出结果:
repeat循环
repeat 循环语句的语法如下:
repeat statementsuntil expressionend repeat
首先,mysql执行statements,然后评估expression。如果expression评估为false,则mysql statements 重复执行直到expression 评估为止true。
因为repeat 循环语句expression 在执行后检查statements,所以repeat循环语句也称为测试后循环。
以下流程图说明了repeat循环语句:
我们可以test_mysql_while_loop使用while loop语句重写上面使用repeat loop语句的存储过程:
delimiter $$drop procedure if exists mysql_test_repeat_loop $$ create procedure mysql_test_repeat_loop ( ) begin declare x int; declare str varchar ( 255 ); set x = 1; set str = ''; repeat set str = concat( str, x, ',' ); set x = x + 1; until x > 5 end repeat; select str;end $$delimiter ;
注意until 表达式中没有分号(;)。
call mysql_test_repeat_loop();
输出结果:
loop,leave和iterate语句
有两个语句允许您控制循环:
leave语句允许您立即退出循环而无需等待检查条件。leave语句的作用类似于php,c / c ++和java等其他语言中的 break 语句。
iterate语句允许您跳过其下的整个代码并开始新的迭代。iterate语句类似于php,c / c ++和java中的continue语句。
mysql还为您提供了loop一个重复执行代码块的语句,并具有使用循环标签的额外灵活性。
以下是使用loop 循环语句的示例:
delimiter $$drop procedure if exists test_mysql_loop $$ create procedure test_mysql_loop() begin declare x int; declare str varchar ( 255 ); set x = 1; set str = ''; loop_label :loop if x > 10 then leave loop_label; end if; set x = x + 1; if ( x mod 2 ) then iterate loop_label; else set str = concat( str, x, ',' ); end if; end loop; select str;end $$delimiter ;
测试一下:
call test_mysql_loop();
在这个例子中,
存储过程仅构造具有偶数的字符串,例如,2,4和6。
我们loop_label 在loop声明之前放置了一个循环标签。
如果值 x 大于10,则由于leave语句而终止循环。
如果the的值x 是奇数,则iterate 语句忽略其下的所有内容并开始新的迭代。
如果the的值x 是偶数,则else语句中的块将构建具有偶数的字符串。
【相关推荐:mysql视频教程】
以上就是mysql存储过程中的循环语句有哪些的详细内容。