MySQL:如何创建添加非空约束的触发器?

时间:2014-05-29 15:07:22

标签: mysql

我创建了customer表,其触发器不允许customer_id列上的空值。它看起来像:

create table customer(
            customer_id varchar(20) UNIQUE,
            customer_name varchar(15) NOT NULL,
            password varchar(10) NOT NULL,
            social_number varchar(14) not null,
            phone_number varchar(13) NOT NULL,
            email varchar(30) NOT NULL,
            address varchar(50) NOT NULL,
            primary key ( social_number )
);

但是,创建以下触发器会导致此错误。

create trigger null_checker 
on customer 
after insert 
as 
delete from customer 
where customer_id is null;
ERROR 1064 (42000): 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 'on customer after insert as delete from customer where customer_id is null' at line 1

有什么问题?我可以使用not null说明符添加非空约束。但我不允许这样做,因为创建触发器是我的任务的一部分。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要使用正确的语法:

create trigger null_checker 
after insert  on customer 
for each row
   delete from customer 
   where customer_id is null;

无法修改来自触发器的同一个表。

没有触发器的解决方案可能是更改sql_mode以避免列中定义的空值。

set sql_mode = 'TRADITIONAL';

当向列中插入不正确的值时,该命令告诉MySQL“给出错误而不是警告”,例如将NULL插入到“非空”列中。

更多信息:http://dev.mysql.com/doc/refman/5.0/en/sql-mode.html