MySQL存储过程procedure

注意,MySQL代码编码格式应该是utf8,推荐notepad++中编辑(记事本、word等不是utf8),否则易出错。

存储过程procudure

类似于函数,把一段代码封装起来。当要执行这一段代码的时候,只需要调用该存储过程即可(可以理解为调用函数)。

在增删调查前,进入数据库(以test数据库为例)。

use test;

 创建存储过程:create procedure

p1存储过程名(函数名)、begin…end$函数体。

分隔符(delimiter):不能再用;做结尾,首先自定义分隔符$,之后再改回;

delimiter $
create procedure p1()
begin
   select * from school;
end$
delimiter ;

创建有参数存储过程p2:筛选school表id>n的内容

delimiter $
create procedure p2(n int)
begin
   select * from school where id>n;
end$
delimiter ;
call p2(2);  #显示id>2的内容

创建多参数存储过程p3:筛选school表id>n或<=n的内容

delimiter $
create procedure p3(n int,j char(1))
begin
   if j=’h’ then
     select * from school where id>n;
   else
     select * from school where id<=n;
   end if;
end$
delimiter ;
call p2(3,’h’);  #显示id>3的内容
#call p2(3,'a'); 显示id<=3的内容

 

调用存储过程:call 存储过程名字();

call p1();

查看现有的存储过程:\G横向显示,方便查看

show procedure status \G;

删除存储过程:drop procedure 存储过程名字;

drop procedure p1;

案例:计算1到n的和。

smallint从-2^15 (-32,768) 到 2^15 - 1 (32,767) 的整型数据。

int从-2^31到2^31的整型数据。

以n=100为例

delimiter $
create procedure p4(n smallint)
begin
declare i int;
declare s int;
set i=1;
set s=0;
while i<=n do
set s=s+i;
set i=i+1;
end while;
select s;      #输出s
end $
delimiter ;

猜你喜欢

转载自www.cnblogs.com/xixixing/p/9720261.html