-- 申明存储过程
DROP PROCEDURE
IF EXISTS test;
CREATE PROCEDURE test (OUT sumtest INT)
BEGIN
SELECT
count(*) INTO sumtest
FROM
student;
SELECT
*
FROM
student
LIMIT 10;
END
-- 调用存储过程
call test(@sum)
-- 获取参数
select @sum
流程控制
if条件
# if...else
if 条件
then 语句1;
else 语句2;
end if;
# if...elseif...else
if 条件1
then 语句1;
elseif 条件2;
then 语句2;
(else 语句3;)
(else 语句4;)
end if;
case条件
第一种语法格式如下:
case 条件判断表达式
when 条件表达式可能的值1 then 语句1;
when 条件表达式可能的值2 then 语句2;
......
else 语句n;
end case;
例子:
case value
when 1 then select 'value is 1';
[when 2 then select 'value is 2';]
[else select 'value is not 1 or 2';]
end case;
第二种语法格式如下
case
when 条件判断语句1 then 语句1;
[when 条件判断语句1 then 语句1;]
[else 语句3;]
end case;
示例:
case
when value is null then select 'value is null';
when value > 0 then select 'value is gteater than 0';
when value < 0 then select 'value is less than 0';
else select 'value is 0';
end case;
loop循环语句用来重复执行某些语句。
loop只是创建循环操作过程,并不进行条件判断。 loop内的语句一直重复执行直到循环被退出,跳出循环过程。 跳出循环用leave
基本语法格式如下:
[loop语句的标注名称:] loop
循环语句;
end loop [loop语句的标注]
示例:
delect id in defult 0;
add_loop: loop
set id = id + 1;
if id >= 10 then leave add_loop;
end if;
end loop add_loop;
repeat语句
repeat语句创建一个带判断条件的循环过程,每次语句执行结束后都会对条件表达式进行判断 若为真,循环结束,否则继续循环操作。
(与C语言中的do…while条件判断相反) 先执行在判断(类似于C语言中的do…while)
基本语法格式
[repeat 语句的标注名称:] repeat
循环语句;
until 循环条件表达式;
end repeat [repeat 语句的标注名称];
while语句
while语句创建一个带条件判断的循环
与repeat的不用是:while语句在执行之前先对指定的条件表达式进行判断。 若为真,继续执行循环,否则退出循环。
基本语法格式如下:
[while 语句的标注名称:] while 循环条件表达式
循环语句;
end while [while 语句的标注名称];