DB2函数简单示例

sql函数必须有返回值
db2中的函数原理同其他编程语言中的函数,均为输入几个参数,同时返回一个值。
下面的例子演示一个寻找某一次考试中成绩最好的学生的姓名。
首先,我们新建一个表score用于表示考试,并插入几条数据:

drop table score;
create table score (
  exam_id int,  -- 考试编号
  student_id int, -- 学生编号
  student_name varchar(50), -- 学生姓名
  point int -- 成绩
);
insert into score values (1,1,'刘玄德',90);
insert into score values (1,2,'关云长',95);
insert into score values (1,3,'张翼德',60);
然后编写用于寻找某场考试的最佳成绩者的姓名的函数,如下:

create or replace function func_best (in in_exam_id int)
returns varchar(50)
begin
  declare v_stu_id int default null;
  declare v_stu_name varchar(50) default null;
  select student_id into v_stu_id from score where exam_id=in_exam_id order by point desc
    fetch first 1 rows only;
  if (v_stu_id is not null) then
    select student_name into v_stu_name
      from score
      where exam_id=in_exam_id and student_id=v_stu_id;
  end if;
  if (v_stu_name is not null) then
    return v_stu_name;
  else 
    return null;
  end if;
end
进行如下测试:

VALUES func_best(1);
可以得到结果如下:

1                                                  
-------------------------------------------------- 
关云长   

转载:https://www.cnblogs.com/zifeiy/p/9014254.html

你可能感兴趣的:(DB2函数简单示例)