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

问题描述 投票:1回答:2

我正在研究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 sql sql-insert database-trigger
2个回答
3
投票

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]';

然后插入视图。如果视图逻辑过滤掉了插入,则插入将失败。


1
投票

您正在检查您的值是否仅包含非字母字符,同时要确保它不包含任何非字母字符。您需要在这里反转逻辑:

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]');
© www.soinside.com 2019 - 2024. All rights reserved.