如果不满足正则表达式,则阻止插入



我正在研究MySQL中的触发器语句,如果人名中有特殊字符,我需要防止插入。

我想做这样的事情:

create trigger verifydata
before insert
on person
for each row
begin
if(not new.name RLIKE '[A-Za-z]') then
signal sqlstate '45000' set message_text = 'Verify name';
end if;
end;@
delimiter ;

但它不起作用。

正确的方法是什么,有什么建议吗?

最新版本的MySQL支持check约束:

alter table person add constraint ck_person_name
check (name not regexp '[^A-Za-z]');

然后,在仍在使用的大多数版本中,您可以通过创建视图来模拟它:

create view v_person as
select p.*
from person p
where p.name not regexp '[^A-Za-z]';

然后插入到视图中。 如果视图逻辑筛选出插入,则插入将失败。

您正在检查您的值是否仅包含非字母字符,同时您要确保它不包含任何字符。您需要在此处颠倒逻辑:

create trigger verifydata
before insert
on person
for each row
begin
if(new.name rlike '[^A-Za-z]') then
signal sqlstate '45000' set message_text = 'Verify name';
end if;
end;
delimiter ;

请注意,如果您运行的是MySQL 8.0.16或更高版本,则可以使用检查约束而不是触发器来执行此操作:

alter table person add constraint check_person_name
check (name not rlike '[^A-Za-z]');

最新更新