Mysql创建一个触发器

时间:2016-05-22 15:41:14

标签: mysql sql triggers

我正在尝试创建一个触发器,但某处出现了错误,我不知道如何正确写入。

CREATE TABLE IF NOT EXISTS Authorization(
userID INT PRIMARY KEY AUTO_INCREMENT,
login VARCHAR(50) NOT NULL,
password VARCHAR(64) NOT NULL,
numberOfFailedAttempts SMALLINT,
lastLogin TIMESTAMP,
lockedAccount BOOLEAN
);


INSERT INTO Authorization SELECT NULL, "test1", SHA2('pass1', 256), 1, NULL,  FALSE;
INSERT INTO Authorization SELECT NULL, "test2", SHA2('pass2', 256), 1, NULL, FALSE;
INSERT INTO Authorization SELECT NULL, "test3", SHA2('pass3', 256), 1, NULL, FALSE;
INSERT INTO Authorization SELECT NULL, "test4", SHA2('pass4', 256), 1, NULL, FALSE;</code>

我会在更新用户检查numberOfFailedAttempts时创建一个触发器。如果numberOfFailedAttempts&gt; 3,然后将lockedAccount更改为true。

CREATE TRIGGER trigger1 AFTER UPDATE ON `numberOfFailedAttempts`
FOR EACH ROW
BEGIN
IF (`numberOfFailedAttempts` > 3) THEN
UPDATE SET `lockedAccount` = 1 WHERE 1, LIMIT 1;
END;

错误是:

#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 'SET `lockedAccount` = 1 WHERE 1, LIMIT 1' at line 5</code>

有人可以帮帮我吗?

编辑:

在这段代码中我遇到了同样的错误。

CREATE TRIGGER trigger1 AFTER UPDATE ON `numberOfFailedAttempts`
FOR EACH ROW
BEGIN
IF (`numberOfFailedAttempts` > 3) THEN
UPDATE `Authorization` SET `lockedAccount` = '1' WHERE     `Authorization`.`userID` = OLD.`userID`;
END;

编辑:

我改变了代码并且它有效。

delimiter //

CREATE TRIGGER trigger1 BEFORE UPDATE ON Authorization
FOR EACH ROW
IF NEW.`numberOfFailedAttempts` > 3 THEN
SET NEW.`lockedAccount` = 1;
END IF;//

2 个答案:

答案 0 :(得分:0)

希望它对你有用。

DELIMITER //

    CREATE TRIGGER trigger_name AFTER UPDATE ON Authorization
    FOR EACH ROW
    BEGIN
        IF (numberOfFailedAttempts > 3) THEN
           UPDATE Authorization SET lockedAccount = 1 WHERE 1 LIMIT 1;
        END IF;
    END //

DELIMITER ;

答案 1 :(得分:-1)

 CREATE TRIGGER trigger1 AFTER UPDATE ON `numberOfFailedAttempts`
 FOR EACH ROW
 BEGIN
 IF (`numberOfFailedAttempts` > 3) THEN
 UPDATE Authorization SET `lockedAccount` = 1 WHERE 1, LIMIT 1;
 END;