2017-04-24 71 views
0

如何在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內的條款我當我插入兩次相同的記錄時觸發調用該觸發器。誰能幫我?這是我的代碼?

+0

我想你也可以通過把唯一約束'(StudentID,SectionID)'實現這個東西。但既然你的要求是一個觸發器,我不會發布這個答案。 –

+0

@ Tim Biegeleisen你能否給我一個暗示,爲什麼第二個INSERT會繼續並再次插入相同的記錄,而不是顯示錯誤消息? – User445555

回答

0

也許你只需要定義的變量studentid更改到別的

DROP TABLE IF EXISTS REGISTRATION; 
CREATE TABLE REGISTRATION(StudentID INT, SectionID INT, Grade DECIMAL(10,2)); 


DROP TRIGGER IF EXISTS Registration_Before_Insert; 
DELIMITER $$ 
     CREATE TRIGGER Registration_Before_Insert 
     BEFORE INSERT ON Registration 
     FOR EACH ROW 
     BEGIN 
     DECLARE counter INT; 
     SELECT COUNT(*) INTO counter FROM Registration WHERE StudentID= NEW.StudentID 
       and new.sectionid = sectionid; 
     IF counter > 0 THEN 
       SIGNAL SQLSTATE VALUE '45000' 
        SET MESSAGE_TEXT= 'The student is already registered for this section'; 
     END IF ; 
     END $$ 

DELIMITER ; 

TRUNCATE TABLE REGISTRATION; 

INSERT INTO Registration(StudentID, SectionID, Grade) 
VALUES(100, 16, 4.2); 

INSERT INTO Registration(StudentID, SectionID, Grade) 
VALUES(100, 16, 4.2); 
+0

@PSalmon,爲什麼放置TRUNCATE語句。我不清楚你爲什麼要這樣做? Truncate語句刪除表中的數據而不是實際的表?你的陳述有效。謝謝你的幫助。 – User445555

+0

你不需要截斷 - 我使用它的習慣來確保表格在測試時爲空。 –