在观看燕十三老师的视频后整理的
定义:
把若干sql封装起来,起个名字就叫过程
把此过程存储在数据库中叫存储过程
存储过程创建语法
create procedure procedurename()
begin
...
一组sql集合
...
end$
查看已经建立的过程
show procedure status;
调用存储过程
call 过程名();
存储过程是可以编程的,可以使用变量,表达式,控制结构来完成复杂的功能
引入变量
用declare声明变量
用法
在begin之后
declare 变量名 变量类型 default 默认值
例如:带有变量的存储过程
create procedure p2()
begin
declare age int default 21;
declare height int default 180;
select councat('年龄是:' age,'身高是',height);
end$
变量运算,赋值
存储过程中,变量可以sql语句中的运算
注意运算的结果进行赋值
set
例如
create procedure p3()
begin
declare age int default 10;
set age = age+10;
select concat('20年后年龄是',age);
end$
if/else 控制结构
if condition then
statement;
else
statemen;
end if;
if condition then
statement;
end if;
例如
create procedure p4()
begin
declare age int default 18;
if age>= 18 then
select '您已经成年';
else
select ('您未成年');
end if;
end$
case 语句
case case_value
when when_value then statemnet_list;
[else statement_list]
end case
例如 测试你喜欢什么动物
create procedure p10()
begin
declare i int default 0;
set i = floor(5*rand());
case i
when 1 then select 'cat';
when 2 then select 'pig';
when 3 then select 'dog';
else select 'dream';
end case;
end$
repeat 语句
repeat
sql statement;
until condition
end repeat;
参数传递
存储过程的()中可以声明参数
语法是[]in/out/inout]参数名 参数类型
例如:判断矩形的''胖瘦''
create procedure p5(in width int,in height int)
begin
if width>height then
select '胖';
elseif width < height then
select '瘦';
else
select '方';
end if;
select concat('面积是',height*width);
end$
call p5(2,3)$
控制结构之循环
while的语法格式
while expression then
...
sqls;
...
end while;
顺序
分支
循环
例如 求1-100的和
create procedure p6()
begin
declare total int default 0;
declare i int default 1;
while i<=100 do
set total = total+i;
set i=i+1;
end while;
select concat('总和是',total);
end$
in型参数 输入参数
例如 求1-n的和
create procedure p7(in n int)
begin
declare total int default 0;
declare i int default 1;
while i<=n do
set total := total+i;
set i := i+1;
end while;
select concat('1-',n,'的总和是',total);
end$
out型参数
向外输出参数,调用的时候需要为改参数填写变量名
例如 求 1-n的和
create procedure p8(in n int,out total int)
begin
declare i int default 1;
set total := 0;
while i<=n do
set total := total +i;
set i := i+1;
end while;
end$
调用:
call p8(100,@sum)$
select @sum $
inout参数用法
例如
create procedure p9(inout age int)
begin
set age := age +20;
end$
调用的时候
先赋值变量,
set @age = 18;
call p9(@age);
select @age;