此问题在此处已有答案:
Delimiters in MySQL(4个答案)
6个月前关闭。
我正在做一个小项目,目前正在建立一个MySQL数据库。不幸的是,这段代码快把我逼疯了:
CREATE TRIGGER main_db.tg_make_competitor
AFTER UPDATE ON main_db.persons
FOR EACH ROW
IF (NEW.permissions LIKE '%Competitor%') && (SELECT COUNT(*) FROM main_db.competitors WHERE competitor_id LIKE NEW.person_id) = 0 THEN
INSERT INTO main_db.competitors(competitor_id)
VALUES (NEW.person_id);
END IF;
我的想法是,当表persons
发生更新时,触发器应该检查记录是否具有Competitor
(SET数据类型)的权限,如果Id = NEW.person_id
的竞争者不存在,则创建一个。
对我来说,一切似乎都很好。但是phpMyAdmin抛出了一个错误:
# 1064 - Something is wrong in your syntax near '' in line 6
第六行是这个部分:
VALUES (NEW.person_id);
我错过了什么吗?我会感激任何提示。提前感谢!
EDIT:人员和竞争对手表结构:
CREATE TABLE main_db.persons
(
person_id INT,
first_name VARCHAR(32) DEFAULT NULL,
last_name VARCHAR(32) DEFAULT NULL,
permissions SET('Standard', 'Competitor', 'Referee', 'Organizer', 'Director') DEFAULT 'Standard',
FOREIGN KEY (person_id) REFERENCES main_db.accounts(account_id) ON DELETE CASCADE,
PRIMARY KEY (person_id)
);
CREATE TABLE main_db.competitors
(
competitor_id INT,
club VARCHAR(256) DEFAULT NULL,
license VARCHAR(32) DEFAULT NULL,
FOREIGN KEY (competitor_id) REFERENCES main_db.persons(person_id) ON DELETE CASCADE,
PRIMARY KEY (competitor_id)
);
EDIT 2:不幸的是,添加了开始... END的代码也不起作用:/
CREATE TRIGGER tg_make_competitor
AFTER UPDATE ON persons
FOR EACH ROW
BEGIN
IF (NEW.permissions LIKE '%Competitor%') && (SELECT COUNT(*) FROM competitors WHERE competitor_id LIKE NEW.person_id) = 0 THEN
INSERT INTO competitors(competitor_id)
VALUES (NEW.person_id);
END IF;
END
解决方案
感谢Ergest Basha和Luuk的回答,原来没有使用自定义分隔符才是问题所在。添加分隔符后,一切都变得很好用。
3条答案
按热度按时间yzxexxkh1#
这段代码可以在PhpMyAdmin中使用:
它只会产生下列警告:
注意:在本地测试时,我确实将
main_db
更改为test
。您可能需要还原该更改。qnzebej02#
您缺少
BEGIN
和END
https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html在MySQL 8.0上测试
du7egjpx3#
您的代码中没有SQL语法错误。我已经在db-fiddle中运行了此代码,它正在工作:
请检查
persion_id
的值