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

时间:2015-11-25 16:11:33

标签: mysql sql database triggers declare

创建触发器时,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_withdrew cadhoc_assigned ,这些字段非常重要:它们的总和绝对不能超过&gt; 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;

1 个答案:

答案 0 :(得分:2)

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

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