|
|
@@ -1004,19 +1004,29 @@ drop view vw_student_score;
|
|
|
下面的存储过程实现了查询某门课程的最高分、最低分和平均分。
|
|
|
|
|
|
```SQL
|
|
|
+drop procedure if exists sp_score_by_cid;
|
|
|
+
|
|
|
delimiter $$
|
|
|
|
|
|
-create procedure sp_get_score(courseId int,
|
|
|
- out maxScore decimal(4,1),
|
|
|
- out minScore decimal(4,1),
|
|
|
- out avgScore decimal(4,1))
|
|
|
+create procedure sp_score_by_cid(
|
|
|
+ courseId int,
|
|
|
+ out maxScore decimal(4,1),
|
|
|
+ out minScore decimal(4,1),
|
|
|
+ out avgScore decimal(4,1)
|
|
|
+)
|
|
|
begin
|
|
|
- select max(score) into maxScore from tb_record where cid=courseId;
|
|
|
- select min(score) into minScore from tb_record where cid=courseId;
|
|
|
- select avg(score) into avgScore from tb_record where cid=courseId;
|
|
|
+ select max(score) into maxScore from tb_record
|
|
|
+ where cid=courseId;
|
|
|
+ select min(score) into minScore from tb_record
|
|
|
+ where cid=courseId;
|
|
|
+ select avg(score) into avgScore from tb_record
|
|
|
+ where cid=courseId;
|
|
|
end $$
|
|
|
|
|
|
delimiter ;
|
|
|
+
|
|
|
+call sp_score_by_cid(1111, @a, @b, @c);
|
|
|
+select @a, @b, @c;
|
|
|
```
|
|
|
|
|
|
> 说明:在定义存储过程时,因为可能需要书写多条SQL,而分隔这些SQL需要使用分号作为分隔符,如果这个时候,仍然用分号表示整段代码结束,那么定义存储过程的SQL就会出现错误,所以上面我们用`delimiter $$`将整段代码结束的标记定义为`$$`,那么代码中的分号将不再表示整段代码的结束,需要马上执行,整段代码在遇到`end $$`时才输入完成并执行。在定义完存储过程后,通过`delimiter ;`将结束符重新改回成分号。
|
|
|
@@ -1026,7 +1036,7 @@ delimiter ;
|
|
|
调用存储过程。
|
|
|
|
|
|
```SQL
|
|
|
-call sp_get_score(1111, @a, @b, @c);
|
|
|
+call sp_score_by_cid(1111, @a, @b, @c);
|
|
|
```
|
|
|
|
|
|
获取输出参数的值。
|
|
|
@@ -1038,7 +1048,7 @@ select @a as 最高分, @b as 最低分, @c as 平均分;
|
|
|
删除存储过程。
|
|
|
|
|
|
```SQL
|
|
|
-drop procedure sp_get_score;
|
|
|
+drop procedure sp_score_by_cid;
|
|
|
```
|
|
|
|
|
|
在存储过程中,我们可以定义变量、条件,可以使用分支和循环语句,可以通过游标操作查询结果,还可以使用事件调度器,这些内容我们暂时不在此处进行介绍。虽然我们说了很多存储过程的好处,但是在实际开发中,如果过度的使用存储过程,将大量复杂的运算放到存储过程中,也会导致占用数据库服务器的CPU资源,造成数据库服务器承受巨大的压力。为此,我们一般会将复杂的运算和处理交给应用服务器,因为很容易部署多台应用服务器来分摊这些压力。
|