2012-07-31 61 views
0

我想創建一個UDATES表的觸發器。我以爲我可以用多個觸發器做到這一點,但我猜MySQL不支持同一類型的一個表上的多個觸發器。所以我被迫把這個包含在一個觸發器中。MySQL觸發器與變量輸入

基本上我試圖根據當前表中更新的內容將新記錄插入到不同的表中。

這裏是我迄今爲止,它的工作原理:

BEGIN 
-- Definition start 
INSERT INTO prices (stationID, price, type, 
prevPrice, prevDate, dateCreated, apiKey, uid) 
VALUES(NEW.stationID, NEW.regPrice, 'reg', OLD.regPrice, 
OLD.regDate, NEW.regDate, NEW.lastApiUsed, NEW.lastUpdatedBy); 
-- Definition end 
END 

我需要發生是type根據用戶提供了什麼類型可能發生改變。由於用戶只能在給定的時間更新一種類型。我正在考慮IF IF THEN聲明,但我不確定如何使其發揮作用。我在想我可以使用列名稱的字符串值在IF聲明中使用,但我不知道這是否可能。

事情是這樣的:

BEGIN 
    -- Definition start 
    IF(type == 'reg') THEN 
    INSERT INTO prices (stationID, price, type, 
    prevPrice, prevDate, dateCreated, apiKey, uid) 
    VALUES(NEW.stationID, NEW.regPrice, 'reg', OLD.regPrice, 
    OLD.regDate, NEW.regDate, NEW.lastApiUsed, NEW.lastUpdatedBy); 
    END IF; 
    -- Definition end 
    END 
+0

你不說你的問題是什麼。你有錯誤嗎?哪一個? – Jocelyn 2012-07-31 21:25:04

回答

0

我能夠使用IF THEN ELSE完成交易。然後我測試了NULL值的條件。如果它是TRUE我然後運行我的代碼。現在由於某種原因,即使UPDATE不止一個,它也只執行一個INSERT命令。對此有何想法?

BEGIN 
-- Definition start 
IF(NEW.regPrice IS NOT NULL) THEN 
INSERT INTO prices (stationID, price, type, 
prevPrice, prevDate, dateCreated, apiKey, uid) 
VALUES(NEW.stationID, NEW.regPrice, 'reg', OLD.regPrice, 
OLD.regDate, NEW.regDate, NEW.lastApiUsed, NEW.lastUpdatedBy); 

ELSEIF(NEW.midPrice IS NOT NULL) THEN 
INSERT INTO prices (stationID, price, type, 
prevPrice, prevDate, dateCreated, apiKey, uid) 
VALUES(NEW.stationID, NEW.midPrice, 'mid', OLD.midPrice, 
OLD.midDate, NEW.midDate, NEW.lastApiUsed, NEW.lastUpdatedBy); 

ELSEIF(NEW.prePrice IS NOT NULL) THEN 
INSERT INTO prices (stationID, price, type, 
prevPrice, prevDate, dateCreated, apiKey, uid) 
VALUES(NEW.stationID, NEW.prePrice, 'pre', OLD.prePrice, 
OLD.preDate, NEW.preDate, NEW.lastApiUsed, NEW.lastUpdatedBy); 
END IF; 
-- Definition end 
END