存储过程?
一组SQL语句集,功能强大,可以实现一些比较复杂的逻辑功能,类似于JAVA语言中的方法。存储过程是一段预编译好的代码,存储过程跟触发器有点类似,都是一组SQL集,但是存储过程是主动调用的,且功能比触发器更加强大,触发器是某件事触发后自动调用
特性
- 有输入输出参数,可以声明变量,有if/else, case,while等控制语句,通过编写存储过程,可以实现复杂的逻辑功能
- 函数的普遍特性:模块化,封装,代码复用
- 速度快,只有首次执行需经过编译和优化步骤,后续被调用可以直接执行,省去以上步骤
一个简单的存储过程
create procedure mypro(in a int, in b int , out sum int)
begin
set sum = a + b;
end;

- 上面是一个简单的a+b=sum的存储过程
- begin end就可以理解为一般写方法套的{},设置变量前面需加上set
- 调用存储过程语法为call 存储过程名(对应的参数)
- select 返回值就能查询存储过程的返回值了
- in表示传入的参数在存储过程里面改变了,在外面查询还是之前的值,不会改变,inout则反之,参数在存储过程里面受到了修改,在外面查询就是修改后的值了,out就是返回值
存储过程中的控制语句
if
create procedure mypro2(in type int)
begin
declare c varchar(500);
if type = 0 then
set c = 'type is 0';
elseif type =1 then
set c = 'type is 1';
else
set c = 'type is not 0 also is not 1';
end if;
select c;
end;

- 上面是一个简单的存储过程if语句的使用
- declare是声明变量区,在存储过程中声明变量需在前面加上declare
- if elseif else end if; 是if控制语句的语法,意思一目了然,由end if;来结束语句
case
create procedure mypro3(in type int)
begin
declare c varchar(500);
case type
when 0 then
set c = 'type is 0';
when 1 then
set c = 'type is 1';
else
set c = 'type is not 0 also is not 1';
end case;
select c;
end;

- 上面是case语句的使用
-case when then else end case; 是case控制语句的语法由end case;来结束语句
存储过程中的循环语句
drop procedure if exists mypro4;
create procedure mypro4(in number int)
begin
declare i int default 0;
declare j int default 0;
while i <= number do
set j = j + i;
set i = i + 1;
end while;
select j;
end;

- 上面是存储过程中while循环的使用
- while 循环条件 do end while;由end while来结束语句
存储过程弊端
- 不同数据库的语法差别很大,移植困难,换了数据库,需要重新编写
- 不好管理,把过多业务逻辑写在存储过程不好维护,不利于分层管理,容易混乱,一般存储过程适用于个别对性能要求较高的业务,其它的必要性不是很大
网友评论