存储过程
-
关键字 Procedure
-
为了完成特定功能的SQL语句集,存储在数据库中,经过第一次编译后,再次调用不需要再次编译,用户只需要指定存储过程名字并给定参数就可以执行完成任务。
-
最主要的还是执行效率和SQL 代码封装
- SQL 代码封装功能
- MySQL 存储过程将业务逻辑封装到存储过程中,便于维护,执行效率高。
- SQL 代码封装功能
-
创建存储过程
-
create procedure 存储过程名([in][out][inout] 参数 datatype) Begin sql语句集 ... ... end
注:存储过程只是先编译sql语句,所以当sql语句中有错误的表或属性时,系统不会提示;而且存储过程会创建成功;只有当调用执行时才会提示错误
例:
-
第一步:修改结束符号
Delimiter #
-
第二步:创建存储过程
create procedure p_a() Begin select*from t_student where sscore>500; select*from t_dept; select*from t_man; end
-
第三步:修改结束符号
Delimiter #;
-
第四步:调用存储过程 call
Call p_a();
-
-
删除存储过程
Drop procedure if exists p_a;
-
带参的存储过程
Create procedure tat(n1 int,n2 int) Begin Declare n3 int; if n1 is null than set n1=10; end if; Set n3 = n1+n2; Select n3 as sum; end
-
存储过程的参数分类:分为3类
-
In:表示需要给存储过程一个值(默认)
create procedure p_c(in n1 int) Begin Select*from t_student where sid=n1; end call p_c(1227);
-
Out:表示存储过程会返回一个值
- 存储过程没有return,但是有into
create procedure p_d(out n2 int) Begin Select max(sscore) into n2 from t_student; end call p_d(@t); //@t全局变量 select @t;
-
Inout:表示既可以传值进去,又可以带值出来
//in、out create procedure p_e(in n1 int, out n2 int) Begin select sscore into n2 from t_student where sid=n1; end call p_e(1220,@i); select @i; //inout create procedure P_k(inout n1 int) Begin select sscore into n1 from t_student where sid=n1; end set @g=1203; call p_k(@g); select @g;
-
-
展示数据库中有哪些存储过程
-
展示存储过程的名字
select name from mysql.proc status where db='数据库名'; select name from mysql.proc status where db='lianxi';
-
展示存储过程的详细信息
show procedure status where db='数据库名'; show procedure status where db='lianxi';
-