1、使用函数完成,通过班级ID查找班级名称 2、通过学生ID查找学生姓名 3、通过班级名称查找,本班学生的姓名 4、使用函数完成插入学生信息 5、使用函数完成删除学生信息 6、使用函数完成删除班级信息,注意删除班级信息前先将本班学生删除。mysql
时间: 2024-11-09 21:24:48 浏览: 12
在MySQL数据库操作中,可以设计如下的函数来完成这些任务:
1. 查找班级名称(通过班级ID):
```sql
CREATE FUNCTION find_class_name(class_id INT) RETURNS VARCHAR(100) AS
BEGIN
RETURN (SELECT class_name FROM classes WHERE class_id = class_id);
END;
```
使用示例: `SELECT find_class_name(1);`
2. 查找学生姓名(通过学生ID):
```sql
CREATE FUNCTION find_student_name(student_id INT) RETURNS VARCHAR(100) AS
BEGIN
RETURN (SELECT student_name FROM students WHERE student_id = student_id);
END;
```
使用示例: `SELECT find_student_name(2001);`
3. 查找班级内的学生姓名(通过班级名称):
```sql
CREATE PROCEDURE find_students_in_class(class_name VARCHAR(100)) BEGIN
SELECT student_name FROM students WHERE class_id IN (SELECT class_id FROM classes WHERE class_name = class_name);
END;
```
调用: `CALL find_students_in_class('一班');`
4. 插入学生信息:
```sql
CREATE PROCEDURE insert_student_info(name VARCHAR(100), class_id INT) BEGIN
INSERT INTO students (student_name, class_id) VALUES (name, class_id);
END;
```
调用: `CALL insert_student_info('张三', 1);`
5. 删除学生信息:
```sql
CREATE PROCEDURE delete_student_info(student_id INT) BEGIN
DELETE FROM students WHERE student_id = student_id;
END;
```
调用: `CALL delete_student_info(2001);`
6. 删除班级及关联的学生信息:
```sql
CREATE PROCEDURE delete_class_info(class_id INT) BEGIN
DECLARE student_count INT DEFAULT 0;
SET @sql = CONCAT('DELETE FROM students WHERE class_id = ', class_id);
SELECT COUNT(*) INTO student_count FROM students WHERE class_id = class_id;
IF student_count > 0 THEN
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
DELETE FROM classes WHERE class_id = class_id;
END;
```
调用: `CALL delete_class_info(1);`
阅读全文