MySQL存储过程案例

MySQL存储过程

**存储过程:**预先编辑好SQL语句的集合,这个集合完成了某项具体的功能集合,需要这个功能的时候,只要调用这个过程就好

创建语法:

create procedure 存储过程的名字(参数列表)
begin
存储过程体(SQL语句的集合);
end

注意:

①参数列表包含三个部分:
参数模式 参数名 参数类型

(比如: in s_name varchar(20) )

参数模式:

in : 该参数可以作为输入,需要调用方传入值来给存储过程 out : 该参数可以作为输出,该参数可以作为返回值给调用方
inout : 该参数既可以做输入,也可以作为输出

②如果存储体只要一句SQL语句,begin和end可以省略,存储体里的sql语句结尾处必须加分号,避免数据库误判为存储过程的结束标记,所以需要我们自定义命令的结尾符号:
delimiter 结尾标记 比如:

delimiter $

如果没有下面用表,先创建

drop table ages;
drop table students;
create table ages(id int,age int);
create table students(id int,name varchar(4),ta_id int);
insert into ages(id,age) values(1,12);
insert into ages(id,age) values(2,22);
insert into ages(id,age) values(3,32);
insert into ages(id,age) values(4,42);
insert into ages(id,age) values(5,52);
insert into ages(id,age) values(6,62);
insert into students(id,name,ta_id) values(1,'任波涛',2);
insert into students(id,name,ta_id) values(2,'田兴伟',1);
insert into students(id,name,ta_id) values(3,'唐崇俊',3);
insert into students(id,name,ta_id) values(4,'夏铭睿',8);
insert into students(id,name,ta_id) values(5,'包琪',1);
insert into students(id,name,ta_id) values(6,'夏雨',10);
insert into students(id,name,ta_id) values(7,'夏铭雨',10);
insert into students(id,name,ta_id) values(8,'白芳芳',6);

存储过程的调用:
call 存储过程名(参数列表);

无参数存储过程:
①delimiter $

②create procedure myp1()

begin
insert into ages(id,`age`) values (11,'12');
insert into ages(id,`age`) values (21,'13');
insert into ages(id,`age`) values (31,'14');
insert into ages(id,`age`) values (41,'15');
end $

调用:

call myp1() $

带in参数模式的存储过程:

案例:通过学生名查询对应的年龄

delimiter $
create procedure myp2(in s_name varchar(10))
begin
select s.name, a.age from students s
inner join ages a
on s.ta_id = a.id
where s.name=s_name;
end $

调用:call myp2(‘任波涛’) $

out参数模式的存储过程:

案例:根据学生姓名,返回对应的年龄

create procedure myp3(in sname varchar(10),out age int)
begin
select a.age into age
from students s
inner join ages a
on s.ta_id = a.id
where s.name=sname;
end $

调用:
call myp3(‘任波涛’,@age) $ #把值取出来放到变量里去
select @age $ #查看值了

案例:根据学生姓名,返回对应的年龄和学生编号

create procedure myp4(in sname varchar(10),out age int,out sid int)
begin
select a.age ,s.id into age,sid
from students s
inner join ages a
on s.ta_id = a.id
where s.name=sname;
end $

调用:call myp4(‘任波涛’,@age,@sid) $
select @age,@sid $

inout参数模式存储过程和删除查看存储过程:

案例:传入a和b两个数,然后让a和b都乘以2后返回

create procedure myp5(inout a int , inout b int)
begin
set a=a*2;
set b=b*2;
end $

调用:
set @a=10$
set @b=20$
call myp5(@a,@b)$
select @a,@b $

delimiter ;

#查看存储过程

show procedure status like 'myp%';

删除存储过程:

drop procedure 存储过程名;
drop procedure myp1; #每次只能删除一个

查看存储过程的信息:

show create procedure 存储名;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值