mysql - 应该在 mysql 中的哪里定义 create TRIGGER

标签 mysql

SQL查询:

CREATE TRIGGER testref BEFORE INSERT ON users
FOR EACH
ROW BEGIN 
INSERT INTO users_roles
SET uid = NEW.uid;

MySQL 说:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3 

最佳答案

drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varchar(32) not null,
created_date datetime not null
)
engine=innodb;

delimiter #

create trigger users_before_ins_trig before insert on users
for each row
begin
  set new.created_date = now();
end#

delimiter ;

insert into users (username) values ('f00'),('bar');

mysql> select * from users;
+---------+----------+---------------------+
| user_id | username | created_date        |
+---------+----------+---------------------+
|       1 | f00      | 2011-03-14 12:39:38 |
|       2 | bar      | 2011-03-14 12:39:38 |
+---------+----------+---------------------+
2 rows in set (0.00 sec)

编辑

触发器就是您所需要的 - 根据您的模式进行适当的编辑!!

delimiter #

create trigger users_before_ins_trig before insert on users
for each row
begin
  set new.created_date = now();
end#

delimiter ;

关于mysql - 应该在 mysql 中的哪里定义 create TRIGGER,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5298462/

相关文章:

mysql - 如何轻松选择或标记 SQL 数据库中的最新重复项

php - 交响乐 2.8 : Any way in doctrine similar to "DAYNAME(date)" of mysql?

mysql - 在ubuntu上安装phpmyadmin后,我忘记了phpmyadmin的用户名和密码。我怎样才能再次恢复这些?

java - 无法从 spring boot docker 容器连接 mysql docker 容器

mysql - 带有sql server的bash中的坏循环变量

java - 从正则表达式得到错误 'repetition-operator operand invalid'

php - 存储过程中的 OUT 参数声明

使用 ODBC 与 MS SQL Server 的 PHP PDO 连接

php - SQL 查询在 phpmyAdmin 中有效,但在 php 中无效

php - 将 PostgreSQL 连接库添加到 Azure 应用服务中