我正在尝试设置执行以下操作的MySQL触发器:
这就是我所拥有的:
CREATE TRIGGER ins_bills AFTER INSERT ON databaseA.bills
FOR EACH ROW
BEGIN
IF NOT EXISTS (SELECT 1 FROM databaseB.bills WHERE billNumber=NEW.billNumber) THEN
INSERT INTO databaseB.bills (billNumber) VALUES (NEW.billNumber)
END IF
END;//
DELIMITER ;
问题是,我无法通过mysql控制台或phpMyAdmin创建它。它在END IF END附近返回语法错误,我确信这是一个分隔符问题。
#1064 - 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 'END IF END' at line 6
我做错了什么?
答案 0 :(得分:2)
如果您有唯一索引,则始终可以进行 INSERT IGNORE
CREATE TRIGGER ins_bills AFTER INSERT ON databaseA.bills
FOR EACH ROW
BEGIN
INSERT IGNORE INTO databaseB.bills (billNumber) VALUES (NEW.billNumber);
END //
答案 1 :(得分:1)
假设你使用//作为分隔符,你只需要在触发器体内的sql stmts末尾使用分号,并在触发器END之后使用//:
CREATE TRIGGER ins_bills AFTER INSERT ON databaseA.bills
FOR EACH ROW
BEGIN
IF NOT EXISTS (SELECT 1 FROM databaseB.bills WHERE billNumber=NEW.billNumber) THEN
INSERT INTO databaseB.bills (billNumber) VALUES (NEW.billNumber);
END IF;
END //