存储过程是预编译好的sql语言的集合 减少编译次数,提高sql语句的重用性。但是在现阶段因为其维护困难及其他一系列的原因,有些时候并不推荐使用

创建

create procedure 存储过程的名字 ( in | out | inout  参数名 参数类型 ) 
begin
    select 字段名 into 输出类型的参数名  from ... 合法的sql语句;
end;

其中 in out inout 表示参数的类型,in为入参,表示调用此存储过程时传进来的参数,out为出参,用于将查询结果保存在out参数上边,调用存储过程之后即可使用; inout具有in 和 out 两个的特点。有一点需要注意的是out参数只能保留单个的结果,如果一条查询语句出来多个结果,则会报错。

调用

call 存储过程名字 ( 参数列表 )
# 一般都是使用 set @自定义名字 = 值  来定义变量

删除

# 一次只能删除一个
drop procedure 存储过程名字

查看

show create procedure 存储过程名字

通常存储过程很少涉及到修改,如果修改存储过程,则先删除然后再创建之。


分支语句

IF 函数

if(exp,exp1,exp2)

简单的双分支函数,类似于三元运算符,可在select或其他地方调用,执行顺序为,exp为真,exp1执行,否则exp2执行。

case

# 第一种 一般用于等值判断 可搭配在select语句中
case exp 
when 值1 then 返回的值或执行的语句
...
else 返回的值
end [case]; # 作为语句时才有case
# 第二种 一般用于区间判断
case 
when 表达式 then 返回值或执行的语句
...
else 返回值或执行的语句
end [case];# 作为语句时才有case

上述两种case若作为表达式可在其他语句中使用,若作为单独的语句则只能在存储过程体函数体中使用,并且要在end后加上case 切每个分支要加上分号,当然前提是使用delimiter重新设置分隔符之后再加分好。
如果when中条件为真,则执行对应的then后边的语句并结束case;若都不满足则执行else中的语句;else可以省略,若省略else 切when中无匹配最终返回null。

示例:

根据传入的成绩显示等级,90-100 -> ‘A’,80-90 -> ‘B’,60-80 -> ‘C’,否则显示’D’

delimiter $
create procedure p1( in score int )
begin
    case 
    when score >= 90 and score <= 100 then select 'A';
    when score >= 80 and score <= 90 then select 'B';
    when score >= 60 and score <= 80 then select 'C';
    else select 'D';
    end case;
end $

if 结构

可以实现多重分支,接近一般编程语言的语法

if 条件 then 语句;
    elseif 条件 then 语句;
    ...
    [else 语句]
    end if;

只能用于函数体存储过程体中。
上边的例子用if分支结构可重写为:

delimiter $
create procedure p1( in score int )
begin
    if score >= 90 and score <= 100 then select 'A';
    elseif score >= 80 and score <= 90 then select 'B';
    elseif score >= 60 and score <= 80 then select 'C';
    else select 'D';
    end if;
end $