存储过程如下:create or replace procedure s_max_grade( teacher_id in number , class_name out varchar)
as
tmp_course number;
tmp_student number;
tmp_class number;
begin
select t.course_id into tmp_course from teacher t where t.teacher_id = teacher_id  ;
select sc.student_id into tmp_student  from student_course sc where sc.grade = (select max(student_course.grade) from student_course where student_course.course_id=tmp_course);
select s.class_id into tmp_class  from student s where s.student_id=  tmp_student;
select c.class_name into class_name from class c where c.class_id = tmp_class;
dbms_output.put_line(class_name);
end;
该存储过程目的是通过输入老师ID,返回该老师所教课程 课程得分最高的那名学生的班级名字,student_course这张表是课程成绩表;
测试的时候出现如下SQL错误:ORA-01422 实际返回的行数超出请求的行数;select into 语句是将一个元素赋值给指定参数,但问题是我一行行select语句依次执行时得到的都是只有一行数据,百思不得其解

解决方案 »

  1.   

    感觉你的第二行很有可能会有问题
    如果实在查不出来 你可以加一个rownum=1
      

  2.   


    如果一个老师上的课不止一门,那么tmp_course就不止一个。
    返回该老师所教课程,得分最高的那名学生的班级名字,你是指这个老师所教授的哪一门课程?
    因为tmp_course不止一个,
    所以:
    select sc.student_id into tmp_student  from student_course sc where sc.grade = (select max(student_course.grade) from student_course where student_course.course_id=tmp_course);
    语句就会出错。
    不知道我这样理解是否正确!
      

  3.   


    select t.course_id into tmp_course from teacher t where t.teacher_id = teacher_id  ;
    select sc.student_id into tmp_student  from student_course sc where sc.grade = (select max(student_course.grade) from student_course where student_course.course_id=tmp_course);我认为1.2可能有多行记录的情况,理由是:
    1. 一个老师可能教多门课程,对应多个course_id。
    2. 分数等于最高分的学生也可能有多个,对应多个student_id。
      

  4.   


    从错误中:
    SQL错误:ORA-01422 实际返回的行数超出请求的行数
    可以看出返回的t.course_id(tmp_course)不唯一,即有多个;
    所以第二条语句的max(student_course.grade)不知道根据那个tmp_course来确定是哪一门课的最高成绩,既有多个最高成绩,这样就会有多个sc.student_id,oracle就不知道tmp_student应该存哪一个sc.student_id了。
    再后面的语句也是一样的,连带错误!
      

  5.   

    一个老师可能教多门课程,对应多个course_id。
    另外一种就是不同的科目 分别有分数最高的学生,返回值也可能不会只有一个 建议楼主好好检查逻辑
      

  6.   

    之前我把course_id设置为teacher这张表的一个外键,虽然course_id在course表中是主键,但在teacher表中不唯一(这点我忘记了!)现在我新增了一个course-teacher 关系表,其实 教师和课程是多对一的关系,将要怎么写这个存储过程才能实现呢。。谢谢
      

  7.   

    各位,谢谢了,是整个表结构设计的不太合理。本是第一次接触存储过程的,想做个测试看看效果,没想到引发了一些问题,考虑不周全;不过更加的明白了些存储过程的预编译。这里特别感谢下minitoy(在水一方),谢谢您的提点