gpt4 book ai didi

mysql - #1064 - 在声明附近创建触发器时出现 MySQL 错误

转载 作者:搜寻专家 更新时间:2023-10-30 20:26:00 26 4
gpt4 key购买 nike

在创建触发器时,MySQL 向我报告了这个错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds
to your MariaDB server version for the right syntax to use near
'DECLARE cadhoc_total INT(1) UNSIGNED;
SET cadhoc_total = NEW.cadhoc_assigned + ' at line 2

这是代码:

DELIMITER $$
DROP TRIGGER IF EXISTS inviter_cadhoc $$
CREATE TRIGGER inviter_cadhoc BEFORE UPDATE ON inviter FOR EACH ROW
DECLARE cadhoc_total INT(1) UNSIGNED;
SET cadhoc_total = NEW.cadhoc_assigned + NEW.cadhoc_withdrew;
IF cadhoc_total > 5 THEN
SIGNAL SQLSTATE '45000' SET message_text = 'Bad update on inviter table: cadhoc must be 5 at maximum';
END IF;
IF NEW.cadhoc_withdrew < OLD.cadhoc_withdrew
SIGNAL SQLSTATE '45000' SET message_text = 'Bad update on inviter table: cannot restore withdrew cadhoc';
END IF;
IF NEW.cadhoc_assigned > OLD.cadhoc_assigned
SIGNAL SQLSTATE '45000' SET message_text = 'Bad update on inviter table: cannot restore assigned cadhoc';
END IF;
$$
DELIMITER ;

感兴趣的表如下,其中cadhoc_withdrewcadhoc_assigned两个字段非常重要:它们的总和绝不能大于5。

CREATE TABLE IF NOT EXISTS Inviter (
nome VARCHAR(10) NOT NULL,
cognome VARCHAR(20) NOT NULL,
email VARCHAR(35) NOT NULL,
#normalizzare
cadhoc_assigned INT(1) NOT NULL DEFAULT 5,
cadhoc_withdrew INT(1) NOT NULL DEFAULT 0,
data_nascita DATE NOT NULL,
PRIMARY KEY (email)
) Engine=InnoDB;

最佳答案

将缺少的 THEN 添加到 IF 子句并用 BEGIN/END block 包装所有内容:

CREATE TRIGGER inviter_cadhoc BEFORE UPDATE ON inviter 
FOR EACH ROW
BEGIN
DECLARE cadhoc_total INT(1) UNSIGNED;
SET cadhoc_total = NEW.cadhoc_assigned + NEW.cadhoc_withdrew;
IF cadhoc_total > 5 THEN
SIGNAL SQLSTATE '45000' SET message_text = 'Bad update on inviter table: cadhoc must be 5 at maximum';
END IF;
IF NEW.cadhoc_withdrew < OLD.cadhoc_withdrew THEN
SIGNAL SQLSTATE '45000' SET message_text = 'Bad update on inviter table: cannot restore withdrew cadhoc';
END IF;
IF NEW.cadhoc_assigned > OLD.cadhoc_assigned THEN
SIGNAL SQLSTATE '45000' SET message_text = 'Bad update on inviter table: cannot restore assigned cadhoc';
END IF;
END

SqlFiddleDemo

关于mysql - #1064 - 在声明附近创建触发器时出现 MySQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33921273/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com