Oracle 11g - 使用RegEx检查约束

时间:2011-10-01 16:38:18

标签: sql regex oracle oracle11g check-constraints

我正在使用Oracle 11g,并试图创建一个表定义创建约束。

我试图添加检查约束来验证某些信息(如电子邮件地址,电话号码等等)

Oracle 11g中是否有允许我做这样的事情?

constraint CK_CONSTRAINT_NAME check (EMAIL like 'REGEX')

我想使用的regEx(从regexLib中获取)是:

^[a-zA-Z][a-zA-Z0-9_\.\-]+@([a-zA-Z0-9-]{2,}\.)+([a-zA-Z]{2,4}|[a-zA-Z]{2}\.[a-zA-Z]{2})$

我认为Oracle 11g(如果我错了,请纠正我)不支持RegEx的这种格式...

我见过使用REGEX_LIKE的方法,但它似乎只适用于WHERE子句。

我想将它作为检查约束而不是触发器或外部函数/脚本。

此外,我在这里读过其他帖子,有人说RegEx'不是验证电子邮件地址格式和此类信息的好方法。评论中没有给出任何理由,我想知道为什么,如果有原因!

2 个答案:

答案 0 :(得分:13)

检查约束遵循与WHERE子句的条件相同的语法规则:

alter table foo
  add constraint check_email 
  check (REGEXP_LIKE(email,'your_regex_goes_here','I')); 

手册中的更多细节:

修改

但是对于您在检查约束中实际使用的内容存在一些限制:

答案 1 :(得分:0)

CREATE TABLE MYTABLE(
  EMAIL VARCHAR2(30) CHECK(REGEXP_LIKE (EMAIL,'^[A-Za-z]+[A-Za-z0-9.]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$'))
);

ALTER TABLE MYTABLE ADD(CONTACT NUMBER(10) CHECK(REGEXP_LIKE(CONTACT,'[0-9]{10}')));


Explanation of Regular Expression
^           #start of the line
  [_A-Za-z0-9-]+    #  must start with string in the bracket [ ], must contains one or more (+)
  (         #  start of group #1
    \\.[_A-Za-z0-9-]+   #     follow by a dot "." and string in the bracket [ ], must contains one or more (+)
  )*            #  end of group #1, this group is optional (*)
    @           #     must contains a "@" symbol
     [A-Za-z0-9]+       #        follow by string in the bracket [ ], must contains one or more (+)
      (         #      start of group #2 - first level TLD checking
       \\.[A-Za-z0-9]+  #        follow by a dot "." and string in the bracket [ ], must contains one or more (+)
      )*        #      end of group #2, this group is optional (*)
      (         #      start of group #3 - second level TLD checking
       \\.[A-Za-z]{2,}  #        follow by a dot "." and string in the bracket [ ], with minimum length of 2
      )         #      end of group #3
$           #end of the line