2012-06-06 97 views
2

我有兩個名爲account和transaction的表。當帳戶插入數據時,我需要自動將數據插入到交易中。我在MySQL中創建了這個觸發器。它給出錯誤1064(語法錯誤)。問題是什麼?觸發器中的語法不正確

CREATE TRIGGER upTransaction AFTER INSERT ON account FOR EACH ROW 
BEGIN 
    INSERT INTO transaction VALUES (2,account.openDate,CURTIME(), 
    account.deposit,account.accNo, 
    "Teller","Cash","Deposit"); 
END 
+0

我想你改變了分隔符吧? – jcho360

+0

您使用的是MySQL還是SQL Server?您的標籤和語法似乎有衝突。 [tag:sql-server]適用於Microsoft SQL Server,不適用於MySQL。 –

回答

1

MySQL的獲取與BEGIN END塊內分號混淆,所以你必須使用分隔符來臨時強制MySQL使用一個不同的分隔符。
文檔:http://dev.mysql.com/doc/refman/5.5/en/create-trigger.html

DELIMITER // 
CREATE TRIGGER upTransaction AFTER INSERT ON account FOR EACH ROW 
BEGIN 
    INSERT INTO transaction VALUES (2,account.openDate,CURTIME(),account.deposit,account.accNo,"Teller","Cash","Deposit"); 
END// 
DELIMITER ; 

你可能需要更換:

 INSERT INTO transaction VALUES (2,account.openDate,CURTIME(),account.deposit,account.accNo,"Teller","Cash","Deposit"); 

有:

 INSERT INTO transaction VALUES (2,NEW.openDate,CURTIME(),NEW.deposit,NEW.accNo,"Teller","Cash","Deposit"); 
0
CREATE 
TRIGGER `event_name` AFTER INSERT 
ON `database`.`table` 
FOR EACH ROW BEGIN 
    -- trigger body 
    -- this code is applied to every 
    -- inserted/updated/deleted row 
END; 

好像你錯過了 '賬戶' 後一個表名。 (編輯:或帳戶之前,數據庫名稱,我不能確定爲哪個帳戶屬於)

+1

使用CREATE TRIGGER時,數據庫名稱是可選的。 – Jocelyn

1

這裏是你原來的觸發

CREATE TRIGGER upTransaction AFTER INSERT ON account FOR EACH ROW 
BEGIN 
    INSERT INTO transaction VALUES (2,account.openDate,CURTIME(), 
    account.deposit,account.accNo, 
    "Teller","Cash","Deposit"); 
END 

更換account.NEW.(可選:更換"'

DELIMITER $$ 
CREATE TRIGGER upTransaction AFTER INSERT ON account FOR EACH ROW 
BEGIN 
    INSERT INTO transaction VALUES (2,NEW.openDate,CURTIME(), 
    NEW.deposit,NEW.accNo, 
    'Teller','Cash','Deposit'); 
END $$ 
DELIMITER ;