SQL也是一门编程语言
存储过程的定义:存储过程是封装了若干条语句存储在数据库中,调用时,这些封装体执行。

基本语法

//创建存储过程的语法:
create procedure procName()
begin
	--sql语句块
end;
//调用存储过程:
call procName();
//查看存储过程
show procedure status;
--或
select name from mysql.proc where db='数据库名' and type="PROCEDURE";
//删除存储过程
drop procedure procName();

存储过程是可以编程的,意味着可以使用变量、表达式、控制结构…来完成复杂的功能。
在存储过程中,使用declare声明变量
格式:declare 变量名 变量类型 [default 默认值]

//eg:
create procedure p1()
begin
	declare age int default 16;
	declare height int default 180;
	select concat("年龄是:", age, "身高是:", height);
end;

call p1();
/*result:
+-------------------------------------------+
| concat("年龄是:", age, "身高是:", height) |
+-------------------------------------------+
| 年龄是:16身高是:180                       |
+-------------------------------------------+
*/

存储过程中,变量可以在sql语句中合法运算,比如 + - * /
赋值格式:set 变量:=expression;

//eg:
create procedure p2()
begin
	declare num int default 1;
	set num:= num+1;
	select concat("1+1=" ,  num);
end;
call p2();
/*result:
+-----------------------+
| concat("1+1=" ,  num) |
+-----------------------+
| 1+1=2                 |
+-----------------------+
*/

给存储过程传参

三种类型的参数:in out inout
in:输入参数
out:输出参数;在存储过程外面可以访问参数,变成一个全局变量
inout:输入输出参数

控制结构

//if/else结构
create procedure p3()
begin
	declare num int default 2;
	if num > 1 then
		select "正确" as a;
	else
		select "错误" as a;
	end if;
end;
//while结构;求1~n之和;in/out实例
create procedure p4(in n int,out total int)
begin
	declare num int default 0;
	set total int default 0;
	
	while num <=n do
		set total:=total+num;
		set num:=num+1;
	end while;
end;

call p5(50,@sumary);
select @sumary; //显示全局变量
/*
+---------+
| @sumary |
+---------+
|    1275 |
+---------+
*/

//case结构
create procedure p6()
begin
  declare pos int default 0;
  set pos:=floor(rand()*5); //产生0~5的随机整数
 
  case pos
  when 1 then select '一' as a;
  when 2 then select '二' as a;
  when 3 then select '三' as a;
  else select '其他' as a;
  end case;
end;

//repeat 循环结构
create procedure p7()
begin
	declare i int default 0;
	
	repeat
		select i;
		set i:=i+1;
		until i>5 end repeat;
end;