求解SQL命令:学生(学号,年龄,性别,系名) 课程(课号,课名,学分,学时) 选课(学号,课号,成绩) 根据上面基本表的信息定义一个存储过程,完成下面功能: 入口参数:学号 1. 根据以上信息建表。 2. 显示学生的选课信息 。3. 如果学生没选课,让他选1号课, 插入一条选课记录,成绩为0。 4. 如果学生所有课都不及格,删掉该学生记录。
时间: 2024-01-03 13:03:35 浏览: 83
以下是实现题目功能的存储过程:
```
CREATE PROCEDURE proc_student_course
@student_id INT
AS
BEGIN
-- 1. Create tables
IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'U' AND name = 'students')
BEGIN
CREATE TABLE students (
student_id INT PRIMARY KEY,
age INT,
gender VARCHAR(10),
department_name VARCHAR(50)
)
END
IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'U' AND name = 'courses')
BEGIN
CREATE TABLE courses (
course_id INT PRIMARY KEY,
course_name VARCHAR(50),
credit INT,
hours INT
)
END
IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'U' AND name = 'student_courses')
BEGIN
CREATE TABLE student_courses (
student_id INT,
course_id INT,
score INT,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (course_id) REFERENCES courses(course_id)
)
END
-- 2. Show student's course information
SELECT c.course_id, c.course_name, c.credit, c.hours, sc.score
FROM courses c
LEFT JOIN student_courses sc ON c.course_id = sc.course_id AND sc.student_id = @student_id
ORDER BY c.course_id
-- 3. Insert record if the student hasn't selected any course
IF NOT EXISTS (SELECT * FROM student_courses WHERE student_id = @student_id)
BEGIN
INSERT INTO student_courses (student_id, course_id, score)
VALUES (@student_id, 1, 0)
END
-- 4. Delete student record if all courses are failed
IF NOT EXISTS (SELECT * FROM student_courses WHERE student_id = @student_id AND score >= 60)
BEGIN
DELETE FROM students WHERE student_id = @student_id
END
END
```
调用存储过程的方法:
```
EXEC proc_student_course @student_id = 1001
```
其中,`@student_id` 参数为传入的学号。
阅读全文