2015-09-08 94 views
0

我想將表的大小限制爲X行(例如,我將使用5)。達到限制時,我想將最舊的行復制到另一個表中,然後將其刪除。我目前有:寫入觸發器語句時出錯

CREATE TRIGGER LimitRows BEFORE INSERT ON MyTable 
FOR EACH ROW BEGIN 
    IF (SELECT COUNT(*) FROM MyTable) >= 5 THEN 

    INSERT INTO HistoryTable 
    SELECT * 
    FROM MyTable A 
    WHERE vhID = A.min(vhID); 

    DELETE FROM MyTable 
    WHERE vhID = min(vhID); 

    END IF;  
END; 

目前,我得到的錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 8

如何正確地寫這個觸發器?另外,如果將表格從100行開始,我怎樣才能將表格裁剪成5行?

回答

1

您需要更改分隔符第一

delimiter | 
CREATE TRIGGER LimitRows BEFORE INSERT ON MyTable 
FOR EACH ROW BEGIN 
    IF (SELECT COUNT(*) FROM MyTable) >= 5 THEN 

    INSERT INTO HistoryTable 
    SELECT * 
    FROM MyTable A 
    WHERE vhID = A.min(vhID); 

    DELETE FROM MyTable 
    WHERE vhID = min(vhID); 

    END IF;  
END 
| 
delimiter ; 

否則觸發器定義將結束在第一;這將使其不完整的。

+0

這解決了我遇到的問題,但不幸的是我的聲明無效。無法修改您要插入的同一張表。儘管如此,由於這解決了這個特定的錯誤,我將其標記爲答案。 – GoldenJoe