如何在BEFORE INSERT觸發器中創建IF EXIST子句以防止插入重複記錄?
-- Create a trigger to prevent a student from registering for a section that the student is already
-- registered for.
USE College ;
DROP TRIGGER IF EXISTS Registration_Before_Insert;
DELIMITER $$
CREATE TRIGGER Registration_Before_Insert
BEFORE INSERT ON Registration
FOR EACH ROW
BEGIN
DECLARE Studentid INT;
SELECT COUNT(*) INTO Studentid FROM Registration WHERE StudentID= NEW.StudentID;
IF NEW.Studentid= 100 AND NEW.SectionID= 16 THEN
\t \t \t \t SIGNAL SQLSTATE VALUE '45000'
\t \t \t \t SET MESSAGE_TEXT= 'The student is already registered for this section';
\t \t END IF ;
END $$
DELIMITER ;
INSERT INTO Registration(StudentID, SectionID, Grade)
VALUES(100, 16, 4.2);
INSERT INTO Registration(StudentID, SectionID, Grade)
VALUES(100, 16, 4.2);
我的工作創造一個BEFORE UPDATE觸發器,以防止學生從該學生已經被註冊一節註冊,但我不知道如何使用IF EXISTS內的條款我當我插入兩次相同的記錄時觸發調用該觸發器。誰能幫我?這是我的代碼?
我想你也可以通過把唯一約束'(StudentID,SectionID)'實現這個東西。但既然你的要求是一個觸發器,我不會發布這個答案。 –
@ Tim Biegeleisen你能否給我一個暗示,爲什麼第二個INSERT會繼續並再次插入相同的記錄,而不是顯示錯誤消息? – User445555