无法在mysql上创建触发器

时间:2014-04-03 17:39:15

标签: mysql sql database

我使用XAMMP和phpmyadmin 3.2.4 - mySQL 5.1.41。

我在mySQL中创建了一个表,我想在tbl_users上创建一个触发器,但是mySQL显示了这个错误:

#1064 - 您的SQL语法出错;查看与您的MySQL服务器版本相对应的手册,以便在'ON TBL_USERS FOR INSERT AS IF附近使用正确的语法(在第1行选择COUNT(*)来自TBL_USERS WHERE USERNAME IN'

CREATE TABLE TBL_USERS
(
ID INT NOT NULL AUTO_INCREMENT,
USERNAME VARCHAR(50) NOT NULL,
PASSWORD VARCHAR(50) NOT NULL,
EMAIL VARCHAR(100) NOT NULL,
STATUS INT DEFAULT 1,
TYPE_USER INT DEFAULT 1,
DISPLAY_NAME VARCHAR(50) NULL,
CONSTRAINT PK_USERS PRIMARY KEY (ID),
CONSTRAINT UN_USERNAME UNIQUE(USERNAME)
)

触发:

CREATE TRIGGER CHECK_USERNAME ON TBL_USERS FOR INSERT
AS
IF(SELECT COUNT(*) FROM TBL_USERS WHERE USERNAME IN (SELECT USERNAME FROM inserted))>1
BEGIN
PRINT 'THIS USERNAME IS EXISTS'
ROLLBACK TRANSACTION
END

1 个答案:

答案 0 :(得分:2)

Trigger activation time can be BEFORE or AFTER. You must specify the activation time when you define a trigger. You use BEFORE keyword if you want to process action prior to the change is made on the table and AFTER if you need to process action after change are made.

试试这样:

create trigger userIns BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
...
END