mysql存储过程

91 阅读2分钟

MySQL5.0版本开始支持存储过程,存储过程就是一组SQL语句集,功能强大,可以实现一些比较复杂的逻辑功能,类似于JAVA语言中的方法,存储过就是数据库SQL与层层面的代码封装与重用

1.有输入输出参数,可以声明变量,有if/else/case/while等控制语句,通过编写存储过程,可以实现复杂的逻辑功能

2.函数的普通特性:模块化,封装,代码复用

3.速度快,只有首次执行需要经过编译和优化步骤,后续被调用可以直接执行

创建存储过程

/*创建*/

create procedure p()
begin
 select count(*) from student;
 end;
 
 call p(); /*调用*/
 
 show create procedure p1;/*查看*/
 
 drop procedure p;/*删除*/
 

定义变量

局部变量

delimiter $$  
create procedure p2()  
begin  
declare var_name01 varchar(20default 'aaa';  -- 声明/定义变量  
set var_naem01 = 'zhangsan'-- 给变量赋值  
select var_name01; -- 输出变量的值  
end $$  
dilimiter ;  
call p2();

用户变量

delimiter $$  
create procedure proc04()  
begin  
set @var_name01 = 'beijing';  
select @var_name01;  
end $$  
dilimiter ;  
call proc04();  
select @var_name01; -- 外部也是可以使用用户变量

系统变量

系统变量分为全局变量和会话变量

 show global variables;/*查看全局变量*/
 select @@global.autocommit;/*查看某个系统变量*/
 set session autocommit=0; /*设置系统变量*/
 

存储过程参数

1803E284B0B9F1E474397B576CFC2353.png

流程控制

if

create procedure p3(in score int,out result varchar(10))
begin
  if score>=90 then set result='优秀';
  elseif score>=80 then set result='良好'; 
  elseif score>=60 then set result='及格';
  else set result='不及格';
  end if;
  end;
  
  call p4(18,@result);
  select @result;

case

 create procedure p4(in month int)
 begin 
   declare result varchar(10);
   case
  when month>=1 and month<=3 then set result='第一季度';
  when month>=4 and month<=6 then set result='第二季度';
  when month>=7 and month<=9 then set result='第三季度';
  when month>=10 and month<=12 then set result='第四季度';
  else set result='输入错误';
 end case;
  select concat('您输入的月份为:',month,'季度为',result);
  end;
  
  call p4(5);
  

循环

while ,repeat,ioop

leave 类似于break,跳出,结束当前所在的循环

iteater 类似于continue,继续,结束本次循环,继续下一次

while循环

create procedure p5(in n int)
begin
 declare total int default 0;
 while n>0 do
   set total=total+n;
   set n=n-1;
   end while;
   select total;
   end;
   
   call p5(10);
   call p5(100);
   

repeat循环

 create procedure p6(in n int)
 begin
  declare total int default 0;
  repeat 
   set total=total+n;
   set n=n-1;
   until n<=0
   end repeat;
   select total;
   end;

 call p6(10);
 call p6(100);

loop循环

 /*计算1到n之间的偶数累加值*/
 create procedure p7(in n int)
 begin
 declare total int default 0;
 
 sum:loop
 if n<=0 then
 leave sum;
 end if;
 
 if n%2=1 then
 set n=n-1;
 iterate sum;
 end if;
 
 set total=total+n;
 set n=n-1;
 end loop sum;
 
 select total;
 end;
 
 call p7(10);
 call p7(100);