MySQL存储过程
存储过程
- 存储过程和其它编程语言的函数很像, 可以用于封装一组特定功能的SQL语句集
- 用户通过
call 存储过程的名称()
来调用执行它
存储过程基本语法
drop table if exists stu;
CREATE TABLE `stu` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `stu` VALUES (1, 'BNTang', 23);
INSERT INTO `stu` VALUES (2, '李四', 18);
定义存储过程
create procedure 存储过程名称(形参列表)
begin
// SQL语句
// ... ...
end;
create procedure show_stu()
begin
select * from stu;
end;
create procedure show_stu_by_id(stuId int)
begin
select * from stu where id = stuId;
end;
调用存储过程
call 存储过程名称(参数);
call show_stu();
call show_stu_by_id(1);
查看存储过程
- 查看MySQL中所有存储过程
show procedure status;
- 查看指定数据库中的存储过程
show procedure status where db='db_name';
- 查看指定存储过程的源代码
show create procedure show_stu;
删除存储过程
drop procedure show_stu;
MySQL中定义变量
🐤全局变量
- 定义: @变量名称;
- 赋值: set @全局变量名称 = 值;
- select 字段名称 into @全局变量名称 from 表名;
🐸局部变量
- 定义: declare 变量名称 数据类型;
- 赋值: set 局部变量名称 = 值;
- select 字段名称 into 局部变量名称 from 表名;
全局变量
set @stuId = 2;
set @stuName = '';
select name into @stuName from stu where id= @stuId;
select @stuName from dual;
局部变量
- 局部变量只能在存储过程和函数中定义, 所以也称之为存储过程变量
create procedure show_stu3()
begin
declare stuId int default 1;
declare stuName varchar(255);
# set stuId = 2;
select name into stuName from stu where id = stuId;
select stuName from dual;
end;
存储过程参数
- MySQL存储过程中的参数分为
in
: 输入参数[默认]out
: 输出参数inout
: 输入输出参数
输入参数
- 外界传递给我们的参数
create procedure show_stu_by_id(in stuId int)
begin
select * from stu where id=stuId;
end;
输出参数
- 存储过程中返回给外界的参数
- MySQL存储过程中不能使用 return 返回值, 需要通过参数来向外返回值
create procedure show_stu_by_id(in stuId int)
begin
set stuName = '';
select name into stuName from stu where id=stuId;
return stuName; # 报错
end;
create procedure show_stu_by_id2(in stuId int, out stuName varchar(255))
begin
select name into stuName from stu where id=stuId;
end;
set @stuName = '';
call show_stu_by_id2(1, @stuName);
select @stuName from dual;
输入输出参数
- 同时具备了输入参数和输出参数的所有功能
create procedure show_stu_by_id3(inout data int)
begin
select age into data from stu where id=data;
end;
set @data = 1;
call show_stu_by_id3(@data);
select @data from dual;