存储过程(Stored Procedure)是在大型数据库系统中,一组为了完成特定功能的SQL 语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。这里例举四个例子,涉及表数据如下:
例1:
drop procedure if exists tewt;
create procedure tewt()
BEGIN
select avg(age) as avgage
from test;
end;
call tewt();
这是一个简单例子,包括创建存储过程,调用过程二部分,没有涉及输入输出参数,直接显示结果。运行结果:
例2:
drop procedure teewt;
create procedure teewt(out mx int,out mi int,out av decimal(8,2))
BEGIN
select avg(age) into av from test;
select max(age) into mx from test;
select min(age) into mi from test;
end;
call teewt(@mx,@mi,@av);
select @mx max,@mi min,@av avg
这是在上个例子前提下扩充,有三个输出参数,分别是最大值,最小值,平均值,代码中包括创建存储过程,调用过程,显示结果三部分。其中:
out,表示为输出参数。
decimal(8,2),浮点数,精度为5,有2位小数。
into av,将结果赋给av
@mx,@开头,表示为变量。
运行结果:
例3:
drop procedure if exists bigthen;
create procedure bigthen(in keynum int,out bigcount int)
begin
select count(id) into bigcount from test where age>keynum;
end;
call bigthen(40,@num);
select @num;
例中有一个输出参数,一个输入参数,求比输入参数大的个数,其中 in ,表示输入参数。结果如下:
例4:
-- 清空可能存在的存储过程
drop procedure if exists tit;
-- 名称:tit
-- 参数:keynum = 关键数字
-- ishappy = 是否活动开心
-- count = 输出数目
create procedure tit(
in keynum int,
in ishappy boolean,
out count decimal(8,0)
)comment '如果活得开心,就年轻十岁,统计年龄小于keynum的值'
BEGIN
-- 定义局部变量 开心增寿默认值,开心人数,不开心时人数
declare happyage int default 10;
declare happycount int;
declare unhappycount int;
select count(*)into unhappycount from test where age < keynum;
select count(*)into happycount from test where (age- happyage) < keynum;
-- 如果活得开心就年轻二十岁.
if ishappy then
select happycount into count;
else
select unhappycount into count;
end if;
end;
call tit(20,true,@count1);
call tit(20,false,@count2);
select @count1 '开心时小于20岁人数',@count2 '不开心小于20岁人数';
此例中增加了注解,逻辑是如果开心,人就年轻10岁,调用该存储过程的时候,传入小于关键数字、是否开心,和传出统计人数。在存储过程里面定义了三个局部变量,还有mysql的逻辑处理ifelse模块,结果如下:
呵呵,结果显示,开心最好。