1.概念
一组为完成特定功能的SQL语句集,存储在数据库中,经过第一次编辑后再次调用不许再次编辑,用户通过指定存储过程的名称并给出参数(如果有参数)来执行它,它可包括逻辑控制语句和数据操作语句,它可接受参数、输出参数、返回单个或多个结果集以及返回值。
2.编写简单存储过程
创建:
create procedure GetUsers()
begin
select * from users;
end;
调用:
call GetUsers();
删除:
drop procedure if exists GetUsers;
3.创建带参数的存储过程
示例1
创建:
create procedure GetScores(
out minScore decimal(8,2),
out avgScore decimal(8,2),
out maxScore decimal(8,2))
begin
select min(score) into minScore from user;
select avg(score) into avgScore from user;
select max(score) into maxScore from user;
end;
调用:mysql中变量都必须以@开始
call GetScores(@minScore,@avgScore,@maxScore);
注:该调用并没有任何输出,只把调用的结果赋值给了调用时出入的变量:@minScore,@avgScore,@maxScore,
如需显示,需用:
select @minScore,@avgScore,@maxScore;
示例2
创建:输入一个用户ID,返回该用户的名字
create procedure GetNameByID(
in userID int
out userName varchar(200))
begin
select name from user
where id = userID
into userName;
end;
调用:
call GetNameByID(1,@userName)
select @userName;
4.创建复杂示例
delimiter //
create procedure GetPriceByID(
in prodID int,
in isDisc boolean,
out prodPrice decimal(8,2))
begin
declare tempPrice decimal(8,2);#声明变量
declare prodDiscRate decimal(8,2);
set prodDiscRate = 0.88;
select price from products
where id = prodID
into tempPrice;
if isDisc then
select tempPrice * prodDiscRate into tmpPrice;
end if;
select tmpPrice into prodPrice;
end;
//
调用:
call GetPriceByID(1,ture,@prodPrice);
select @prodPrice;
网友评论