创建一个存储过程p2,调用这个存储过程时能够输出所有学生的信息,包括选课信息
时间: 2024-06-08 20:10:05 浏览: 60
存储过程调用
假设有以下表结构:
学生表(students):
- id(学生ID)
- name(学生姓名)
- age(学生年龄)
选课表(course_selections):
- id(选课记录ID)
- student_id(学生ID)
- course_id(课程ID)
课程表(courses):
- id(课程ID)
- name(课程名称)
- teacher(授课教师)
可以创建如下的存储过程p2:
```
DELIMITER //
CREATE PROCEDURE p2()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE student_id INT;
DECLARE student_name VARCHAR(255);
DECLARE student_age INT;
DECLARE course_name VARCHAR(255);
DECLARE course_teacher VARCHAR(255);
DECLARE course_selection_cursor CURSOR FOR
SELECT students.id, students.name, students.age, courses.name, courses.teacher
FROM students
JOIN course_selections ON students.id = course_selections.student_id
JOIN courses ON course_selections.course_id = courses.id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN course_selection_cursor;
SELECT '学生ID', '学生姓名', '学生年龄', '选课课程名称', '授课教师';
read_loop: LOOP
FETCH course_selection_cursor INTO student_id, student_name, student_age, course_name, course_teacher;
IF done THEN
LEAVE read_loop;
END IF;
SELECT student_id, student_name, student_age, course_name, course_teacher;
END LOOP;
CLOSE course_selection_cursor;
END //
DELIMITER ;
```
当调用p2存储过程时,会输出所有学生的信息,包括选课信息。
阅读全文