Oracle创建函数例子

编写一个函数计算学生某一门课程在班级内的排名。

表结构如下:

create or replace function fun_score_rank(
p_in_stuid in number,--学号
p_in_courseid in  number --课程ID
)
return number
is
ls_pm number:=0;
ls_score number:=0;
begin
  --获取该学生的成绩
  select t.score into ls_score from score_ys t
   where t.stuid = p_in_stuid
     and t.courseid = p_in_courseid;
  --获取成绩比该学生高的人数
  select count(1) into ls_pm from score_ys t
   where t.courseid = p_in_courseid
   and  t.score>ls_score;
   --得到该学生的成绩排名
   ls_pm:=ls_pm+1;
   return ls_pm;
exception
  when no_data_found  then
     dbms_output.put_line('该学生的课程:'||p_in_courseid|| '的成绩在成绩表中找不到');
end;

使用函数

select fun_score_rank('1001','2') 排名1, fun_score_rank('1002','1') 排名2 from dual;

猜你喜欢

转载自www.cnblogs.com/fangjb/p/12582813.html