Py学习  »  DATABASE

在mysql中,regexp alwasy的计算结果为true

kravb • 5 年前 • 1166 次点击  

我有一个触发器,它只允许在regexp表达式计算为true时插入。然而,这个表达似乎总是正确的。

即使我插入了表达式中任何地方都不允许的随机字符,也会插入一行。

regex表达式可用于在线regex检查程序。但在调用mysql触发器时永远不会失败。

开始

-- find out what is the labelType based on the labelID
SET @labelType = ( SELECT labelTypeID 
                   FROM customer.label
                   WHERE labelID = NEW.labelID);

IF @labelType = 2 THEN -- 2 = date format in YYYY-MM-DD (ie: 2019-05-05)
    IF NEW.labelValue NOT REGEXP '[12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])' THEN
        SET @err_msg = CONCAT(NEW.labelValue, ' Invalid date format. Please make sure it conforms to YYYY-MM-DD.');

        SET @err_msg = left(@err_msg, 128);
        SIGNAL SQLSTATE '41000'
        SET MESSAGE_TEXT = @err_msg;
    END IF;
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43622
 
1166 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Tim Biegeleisen
Reply   •   1 楼
Tim Biegeleisen    6 年前

这个 REGEXP 早于8+的MySQL版本中的运算符不支持 \d 代表一个数字。相反,你应该使用 [0-9] :

IF NEW.labelValue NOT REGEXP '[12][0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])'
THEN
    SET @err_msg = CONCAT(NEW.labelValue, ' Invalid date format. Please make sure it conforms to YYYYMMDD.');

下面是一个演示,说明上面的regex实际上可以在mysql 5.7中正常工作:

Demo