students(student_id, name, year, GPA, programs_code) instructors(instructor_id, name, title, salary, programs_code) programs(code, name, division, instructor_id) course(course_name, credit, domain, course_number) enroll(student_id, instructor_id, course_name) 1. Create tables according to the schema. 2. Use check or assertion to make sure instructors salary > 5000. 3. Use trigger to deal with cascade delete.
时间: 2024-02-27 16:54:38 浏览: 58
I apologize if my previous response was not satisfactory. Here is the updated SQL code with the trigger to deal with cascade delete:
```
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(50),
year INT,
GPA FLOAT,
programs_code INT,
FOREIGN KEY (programs_code) REFERENCES programs(code) ON DELETE CASCADE
);
CREATE TABLE instructors (
instructor_id INT PRIMARY KEY,
name VARCHAR(50),
title VARCHAR(50),
salary FLOAT,
programs_code INT,
CONSTRAINT check_salary CHECK (salary > 5000),
FOREIGN KEY (programs_code) REFERENCES programs(code) ON DELETE CASCADE
);
CREATE TABLE programs (
code INT PRIMARY KEY,
name VARCHAR(50),
division VARCHAR(50),
instructor_id INT,
FOREIGN KEY (instructor_id) REFERENCES instructors(instructor_id) ON DELETE CASCADE
);
CREATE TABLE course (
course_name VARCHAR(50) PRIMARY KEY,
credit INT,
domain VARCHAR(50),
course_number INT
);
CREATE TABLE enroll (
student_id INT,
instructor_id INT,
course_name VARCHAR(50),
FOREIGN KEY (student_id) REFERENCES students(student_id) ON DELETE CASCADE,
FOREIGN KEY (instructor_id) REFERENCES instructors(instructor_id) ON DELETE CASCADE,
FOREIGN KEY (course_name) REFERENCES course(course_name) ON DELETE CASCADE,
PRIMARY KEY (student_id, instructor_id, course_name)
);
CREATE OR REPLACE FUNCTION delete_programs()
RETURNS TRIGGER AS $$
BEGIN
DELETE FROM programs WHERE instructor_id = OLD.instructor_id;
RETURN OLD;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER cascade_delete
AFTER DELETE ON instructors
FOR EACH ROW
EXECUTE FUNCTION delete_programs();
```
In the `students` and `instructors` tables, I've added foreign key constraints that reference the `programs` table with `ON DELETE CASCADE` option. This means that when a program is deleted from the `programs` table, all the related students and instructors will also be deleted from their respective tables.
I've also added a trigger `cascade_delete` that is executed after a row is deleted from the `instructors` table. This trigger calls a function `delete_programs` that deletes all the related programs from the `programs` table.
Let me know if you have any further questions!
阅读全文