过程:封装了若干条语句,调用时,这些封装体执行

函数:是一个由返回值的’过程‘

过程是没有返回值的函数

 

我们把若干条sql封装起来,起个名字---过程

把此过程存储在数据库中------存储过程

 

存储过程的创建语法:

create procedure procedureName()

begin

-----sql语句;

end$

我们创建一个简单的存储过程:

create procedure p1()
begin
select 2+3
end$

调用存储过程:

call p1()$

存储过程是可以编程的,意味着可以使用变量,表达式,控制结构来完成复杂的功能

在存储过程中,用declare声明变量

格式:declare 变量名 变量类型[default 默认值]

create procedure p2()
begin
   declare age int default 18;
   declare height int default 180;
   select concat('年龄是',age,'身高是',height); 
end$

我们调用这个p2存储过程看看:

 

存储过程中,变量可以进行sql语句中的合法运算,如+-*/

注意的是,运算的结果如何赋值给变量:

set 变量名 := expression

create procedure p3()
begin
declare age int default 18;
set age :=age+20;
select concat('20年后年龄是',age);
end$

if/else 控制:

create procedure p4()
begin
declare age int default 18;
if age>=18 then
select '已成年';
else
select '未成年';
end if;
end$

可以看到我们的存储过程没有传参数,接下来我们就建立一个可以传参的存储过程:

传参的语法  [in/out/inout] 参数名 参数类型

create procedure p5(width int, height int)
begin
select concat('你的面积是',width*height)as area;
if width>height then
select '你挺胖';
elseif width<height then
select '你挺瘦';
else
select '你挺方';
end if;
end$

我们给里面传入参数(3,4):

我们都知道控制结构有三大类:顺序,选择和循环

我们现在来写一个带有循环控制结构的存储过程:

create procedure p6()
begin
declare total int default 0;
declare num int default 0;
while num<100 do
set num:=num+1;
set total:=total+num;
end while;
select total;
end$

上面的是我们输出1到100的和,接下来我们在p6的基础上稍作改进写一个p7:输入一个参数N,得到1到N的和:

create procedure p7(in N int)
begin
declare total int default 0;
declare num int default 0;
while num<N do
set num:=num+1;
set total:=total+num;
end while;
select total;
end$

in 表示我们是输入参数

我们接下来看输出参数:

create procedure p8(in n int,out total int)
begin
declare num int default 0;
set total:=0;
while num<n do
set num:=num+1;
set total:=total+num;
end while;
end$

其实out就是往外面输出参数,我们给个变量来接受它。

我们在看一下inout型参数:

create procedure p9(inout age int)
begin
set age:=age+20;
end$

在这里我们要先声明一个变量,然后调用存储过程,然后再输出它

posted on 2019-08-07 18:11  阿尔托莉雅`潘德拉贡  阅读(394)  评论(0编辑  收藏  举报