2014-10-20 70 views
-2

我有一個帶有屬性值的表,eventid。我想讓觸發器代碼檢查一個特定的事件是否已經被插入了三次,如果是,拋出和異常每次都有一個相同的eventid值插入到表中。觸發重複屬性sql

我使用下面的代碼:

CREATE TRIGGER 'timeslotattendantcheck' 
BEFORE INSERT ON 'attendants' 
FOR EACH ROW 
DECLARE @v_dup int; 
BEGIN 
    SELECT @v_dup=COUNT(*) from attendants where attendant=:NEW.attendant; 
    if v_dup > 3 then 
     Raise_Application_Error (-20100, 'Too many attendants for one time slot. The insert is cancelled.'); 
    end if; 
end; 
+1

什麼是你的問題? – 2014-10-20 18:28:02

+0

這裏有很多語法錯誤!請參閱下面的回答 – Barranka 2014-10-20 18:33:03

+0

mysql服務器拋出一個異常「你的SQL語法有錯誤;查看與你的MySQL服務器版本相對應的手冊,以便在'Declare @vdup int DEFAULT 0; BEGIN SELECT @v_dup附近使用正確的語法= count(*)from ... – gnas 2014-10-20 18:36:16

回答

0

當你定義一個觸發(或程序),您需要更改默認的查詢分隔符,然後你必須將其恢復到;(和這些報價...他們必須回覆')。

此外,不要使用用戶變量(@變量);使用局部變量(除非需要使用過程外的值)。並在begin...end塊內聲明變量

改正的代碼:

delimiter $$ 
CREATE TRIGGER `timeslotattendantcheck` 
BEFORE INSERT ON `attendants` 
FOR EACH ROW 
BEGIN 
    DECLARE v_dup int; 
    SET v_dup = (SELECT COUNT(*) from attendants where attendant = NEW.attendant); 
    if v_dup > 3 then 
     SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Too many attendants for one time slot. The insert is cancelled.'; 
    end if; 
end $$ 
delimiter ; 

相關鏈接:

+0

#1064 - 您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'(-20100,' ');' – gnas 2014-10-20 18:34:32

+0

剛剛編輯...引發錯誤,您使用'signal' – Barranka 2014-10-20 18:35:00

+0

#1064 - 您的SQL語法有錯誤;檢查與您的MySQL服務器版本對應的手冊在'SQLSTATE'45000'附近使用正確的語法'SET MESSAGE_TEXT ='一個時間段的服務員太多'在線8 – gnas 2014-10-20 18:37:35