适用于加拿大邮政编码+美国邮政编码的SQL约束?

时间:2018-09-21 05:14:46

标签: regex oracle oracle11g regexp-like

我已经为加拿大邮政编码创建了约束条件,并且可以正常工作,但是当我输入1234567之类的美国邮政编码时,记录仍会添加到其中。我正在寻找一种方法来更改我的约束,因此它仅接受5 数字吗?

Postal_Code varchar2(7) Constraint NN_Investor_PostalCode Null,
Constraint CK_Investor_PostalCode check 
(REGEXP_LIKE (Postal_Code, '[A-Z][0-9][A-Z] [0-9][A-Z][0-9]') 
    or REGEXP_LIKE (Postal_Code, '[1-9][0-9][0-9][0-9][0-9]')), 

1 个答案:

答案 0 :(得分:0)

您可以尝试

REGEXP_LIKE (Postal_Code, '[A-Z][0-9][A-Z] [0-9][A-Z][0-9]') 
        or ( REGEXP_LIKE (Postal_Code, '^[1-9][0-9]{4}') and length(Postal_Code)=5

作为 check 约束。

示例演示:

with t(Postal_Code) as
(
 select '12345'   from dual union all
 select '32045'   from dual union all 
 select '1234567' from dual union all
 select '123456'  from dual union all
 select  '01234'  from dual 
)
select * 
  from t
 where REGEXP_LIKE (Postal_Code, '[A-Z][0-9][A-Z] [0-9][A-Z][0-9]') 
    or ( REGEXP_LIKE (Postal_Code, '^[1-9][0-9]{4}') and length(Postal_Code)=5 );

POSTAL_CODE
----------- 
  12345
  32045