I was looking for a way to set a trigger for my table that acts like cascade.
CREATE TABLE Class(
Class_ID BIGINT,
c_InstrumentID BIGINT NOT NULL,
c_StudentID BIGINT,
c_InstructorID BIGINT NOT NULL,
c_InstituteId BIGINT NOT NULL,
c_TermSeason NVARCHAR(10),
c_TermYear INT,
--StartSession and FinalSession in Add Column
c_TimeOfClass TIME NOT NULL,-- in add constraint
c_DayOfClass NVARCHAR(30),-- in add constraint
c_Eligibility INT,-- in add constraint 1 or 0 date current > finalsession => 0
c_RemainingSession INT,
CONSTRAINT cons_Season CHECK(c_TermSeason IN ('Spring', 'Summer', 'Fall', 'Winter')),
CONSTRAINT cons_TimeClass CHECK(c_TimeOfClass BETWEEN '08:30:00' AND '20:30:00'),
CONSTRAINT cons_RemainSession CHECK (c_RemainingSession BETWEEN -1 AND 13),--Update CONSTRAINT,
FOREIGN KEY(c_InstrumentID) REFERENCES Instrument(Instrument_ID) ON DELETE NO ACTION,
FOREIGN KEY(c_StudentID) REFERENCES Student(Student_ID) ON DELETE NO ACTION,
FOREIGN KEY(c_InstructorID) REFERENCES Instructor(Instructor_ID) ON DELETE NO ACTION,
FOREIGN KEY(c_InstituteId) REFERENCES Institute(Institute_ID) ON DELETE NO ACTION,
PRIMARY KEY (Class_ID)
)
Now I have a trigger for deleting Student.
CREATE OR ALTER TRIGGER update_DeleteStudent on Student
AFTER DELETE
AS
BEGIN
DELETE Class
FROM Class C INNER JOIN deleted d
ON C.c_StudentID = d.Student_ID
WHERE DATEDIFF(WEEK, C.Final_Session, GETDATE()) >= 0
UPDATE Class
SET c_StudentID = NULL
WHERE c_StudentId IN (SELECT Student_ID FROM deleted) AND DATEDIFF(WEEK, GETDATE(), Final_Session) > 0
END;
But it sounds that there is a problem in deleting student id = 1
.
Does anybody know what can I do in this situation?
I don't want to use ON DELETE CASCADE
.