概述
在mysql中可以使用if/case/loop/leave/iterate/repeat/while语句进行流程控制。
if语句
if语句实现条件判断,类似高级语言(c/c++/php/java等)中的if语句。
if search_condition then
statement_list
[elseif search_condition then statement_list]...
[else statement_list]
end if
举例
if mobile='13911113222' and psw='720717' then set useridx = 10008888; else if mobile='13911113333' and psw='720717' then set useridx = 10006666; else select UserID into useridx from User_ID order by rand() limit 1; end if;
case语句
case实现比if更复杂的一些分支选择,类似与高级语言中的 switch语句。
case case_value when when_value then statement_list [when when_value then statement_list]... [else statement_list] end case
举例
case sid when 2 then set @x1 = 2; else set @x1 = 1; end case
loop、leave、iterate语句
loop实习简单的循环,退出循环条件需要其他语句定义。类似与汇编中的loop,类似于高级语言中的goto语句。
#loop语法 [begin_label:] loop statement_list end loop [end_label]
leave语句用来从流程结构中跳出来,类似于高级语言中的break语句。 iterate语句用来跳过当前循环的剩下语句,直接进入下一轮循环。类似与高级语言中的continue语句。
举例
set @x=0; set @x2=0; ins:loop set @x=@x+1; if @x=10 then leave ins; elseif mod(@x,2)=0 then iterate ins; end if set @x2=@x2+1; end loop ins;
上面的例子,表示变量x循环加1,当x=10,退出循环。当x取2的模不为0时候,变量x2加1。
repeat语句
repeat语句是有条件的循环控制语句,类似与高级语言中的do...while语句。
[begin_lable:] repeat statement_list until search_condition end repeat [end_lable]
举例
set @x=0; repeat set @x = @x +1; until @x>10 end repeat;
while语句
while语句是实现有条件的循环控制语句,类似与高级语言中的while语句。
[begin_label:] while search_condition do statement_list end while [end_label]
举例
set @x=10; while @x1<0 do set @x = @x-1; end while;