MySQL:如何创建添加NOTNULL约束的触发器?
我已经创建了MySQL:如何创建添加NOTNULL约束的触发器?,mysql,Mysql,我已经创建了customer表,该表的customer\u id列上有一个不允许空值的触发器。它看起来像: create table customer( customer_id varchar(20) UNIQUE, customer_name varchar(15) NOT NULL, password varchar(10) NOT NULL, social_number varchar(14)
customer
表,该表的customer\u 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
你怎么了?我可以使用
notnull
说明符添加notnull约束。但我不允许这样做,因为创建触发器是我任务的一部分。任何帮助都将不胜感激。您需要使用正确的语法:
create trigger null_checker
after insert on customer
for each row
delete from customer
where customer_id is null;
但是您不能从触发器修改相同的表
没有触发器的解决方案可能是更改sql\u模式
,以避免在列中定义空值
set sql_mode = 'TRADITIONAL';
当向列中插入不正确的值时,该命令对MySQL说“给出一个错误,而不是一个警告”,就像向“notnull列”插入NULL一样
更多信息:你为什么要坚持扣动扳机?将NOT NULL约束添加到字段中,DBE将通过防止在表上执行触发器时插入NULL值作为旁注来解决问题。您不能在同一个表上的触发器中运行另一个查询来插入/删除/更新。您说您给出的语法是正确的,但在我使用该触发器时给出了一个错误?是,因为您不能从自己的触发器修改(更新/删除)同一个表。建议的解决方案不使用触发器,而是更改sql模式以防止空插入。您需要将NOTNULL添加到customer_id字段。