mysql的基本流程控制语句

--  开始我们的mysql控制语句
由于近期比较忙,所现在才开始跟新mysql心得,我们来谈谈mysql的流程语句一下代码在控制台或者
如果对mysql delimiter分界符不太懂得,先看这篇博客: mysql 分界符delimiter介绍
一、if语句
形式如下:
if condition then
...
[else condition then]
...
[else]
...
end if


Example:
drop procedure if exists test_if;
delimiter // -- 分界符
create procedure test_if(in x int)
begin
if x=1 then
select 'OK';
elseif x=0 then
select 'No';
else 
select 'good';
end if;
end
//
delimiter ;
call test_if(0);

二、case语句
case语句为多分枝语句结构,改语句首先从when后的value中查找与case后的value相等的值,如果找到,则执行该分支语句,否则执行else语句,形式如下:
case value
when value then ...
[when value then...]
[else...]
end case

其中,value参数表示判断的变量;when...then中的value表示变量的取值。case语句还有另外一种语法表示结构:
case 
when value then...  -- 此处的value可以为一个条件condition
[when value then...]
[else...]
end case

example:
drop procedure if exists test_case;
delimiter //
create procedure test_case(in x int)
begin
case x
when 1 then select 'OK';
when 0 then select 'No';
else select 'good';
end case;
end
//
delimiter ;
call test_case(9);
三、while循环
改语句形式如下
while condition do
...
end while

exmaple:
drop procedure if exists test_while;
delimiter //
create procedure test_while(out sum int)
begin
declare i int default 1;
declare s int default 0;
while i<=10 do
set s = s+i;
set i = i+1;
end while;
set sum = s;
end;
//
delimiter ;
call test_while(@s);
select @s;

四、loop循环
该循环没有内置循环条件,但可以通过leave 语句退出循环。表示形式如下:
loop
...
end loop
example:
drop procedure if exists test_loop;
delimiter //
create procedure test_loop(out sum int)
begin
declare i int default 1;
declare s int default 0;
loop_label:loop
set s = s+i;
set i = i+1;
if i>10 then leave loop_label;
end if;
end loop;
set sum = s;
end;
//
delimiter ;
call test_loop(@s);
select @s;

五、repeat循环语句
该语句执行一次循环体,之后判断condition条件是否为真,为真则退出循环,否则继续执行循环体。repeat语句的表示形式如下。
repeat
...
until condition
end repeat
eample:
drop procedure if exists test_repeat;
delimiter //
create procedure test_repeat(out sum int)
begin
declare i int default 1;
declare s int default 0;
repeat
set s = s+i;
set i = i+1;
until i>10 -- 此处不能有分号
end repeat;
set sum = s;
end;
//
delimiter ;
call test_repeat(@s);
select @s;

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值