在一些语言中,有一个概念叫“过程”和“函数”,在PHP中,没有过程,只有函数
把若干条sql语句封装起来----过程
把此过程存储在数据库中-----存储过程
存储过程的创建语法:
create procedure procedureName()
begin
---sql 语句
end$
查看已有的procedure命令-----show procedure status;
删除:drop p1;
调用存储过程---call procedure();
存储过程是可以用来编程的,意味着可以使用变量,表达式,控制结构来完成复杂的功能
在存储工程中,用declare声明变量,在begin之后声明
格式:declare 变量名 变量类型 【default 默认值】;
存储过程中,
1.变量可以做sql语句中合法的运算,如加减乘除,注意的是运算的结果如何赋值给变量
格式:set 变量名 := expression(表达式)
set age := age+18;
2.if/else控制结构
格式:if condition then
statement
else
end if;
3.给存储过程传参存储过程的括号里,可以声明参数
格式:【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$
调用p5:call p5(3,4);
4.循环
例子:1-100相加
create procedure p6()
begin
declare total int default 0;
declare num int default 0;
while num<=100 do-------注意最后是否能加到100
set total := total+num;
set num := num+1;
end while;
select total;
end$
求1到N的和---只需create procedure p6( in n int)改动p6这里,把里面的100替换为n即可
参数类型分为三种:
1 "in" argu is input type,which can get the value we input,是调用的时候传进去的参数
2 "out" out是返回给我们数据,赋值给定义为out的变量
3 ”inout“ 就是既能传进去一个参数,也能输出来的参数
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$
call p8(100,@sumary);-----@total是定义一个变量
最后查看sumary值即可
create procedure p9( inout age int)
begin
set age := age + 20;
end$
调用:调用之前先给变量赋值
set @curage=18;
call p9(@curage);
case结构的用法:
create procedure p10()
begin
declare pos int default 0;
pos = floor(5*rand());----0到5,floor取整,rand本身是取0到1
case pos
when 1 then select 'still flying';
when 2 then select 'fall in sea';
else select 'i dont know';
end case;
end$
repeat 循环
语法:repeat
sql statement
.......
until condition end repeat;
例子
create procedure p11()
begin
declare i int default 0;
repeat
select i;
set i :=i+1;
until i>10 end repeat;
end$