Oracle:检查varchar2中字母和数字字符的约束

时间:2013-08-07 10:41:10

标签: sql oracle oracle11g character check-constraints

所以我想检查varchar2的格式是4个字母字符,然后是3个数字字符,例如AABB123或LMNO987

到目前为止,我已经尝试过:

CONSTRAINT Code_Check check (REGEXP_LIKE(Code,'[^A-Z][^A-Z][^A-Z][^A-Z][0-9][0-9][0-9]'))

CONSTRAINT Check_Code check (Code LIKE '[^A-Z][^A-Z][^A-Z][^A-Z][0-9][0-9][0-9]'

CONSTRAINT Check_Code check (Code LIKE '[A-Z][A-Z][A-Z][A-Z][0-9][0-9][0-9]')

CONSTRAINT Check_Code check (Code regexp_LIKE '[A-Z][A-Z][A-Z][A-Z][0-9][0-9][0-9]')

CONSTRAINT Check_Code check (Code LIKE '[^A-Z]{4}[0-9]{3}')

但只是得到错误:

insert into Table1 (Code) values ('HELP555')
Error report:
SQL Error: ORA-02290: check constraint (BOB.TABLE1_CHECK_CODE) violated
02290. 00000 - "check constraint (%s.%s) violated"
*Cause: The values being inserted do not satisfy the named check
*Action: do not insert values that violate the constraint.

1 个答案:

答案 0 :(得分:2)

正则表达式不对,你使用的方式非常麻烦。

相反,您可以选择使用POSIX character classes。在您的具体情况下,它将是这样的:

[[:alpha:]]{4}[[:digit:]]{3}

所以约束检查是

CONSTRAINT Code_Check check (REGEXP_LIKE(Paper_Code,'[[:alpha:]]{4}[[:digit:]]{3}')

这将检查有4个字母字符,后跟3个数字。

SQL fiddle&更多信息,请访问regexp cheatsheet