Search code examples
mysqlsqldatabasetriggersdeclare

#1064 - MySQL error while creating a trigger near a declare


While creating a trigger I had this error reported me by 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

This is the code:

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 ;

The interested table is the following, in which there are two fields that are the cadhoc_withdrew and cadhoc_assigned that are very important: theyre sum must never go > 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;

Solution

  • Add missing THEN to IF clause and wrap everything with 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