日期:2014-05-18  浏览次数:20500 次

sql check约束
大家好,我建了一个表(table),表中的一个字段用了check约束,定义如下 check('[A-Z]{3}'),但插入"ABC"时却报错,我知道用将check改为('[A-Z][A-Z][A-Z]')可以解决问题,但是在sql中是否有方法类似于Java的正则表达式?假如没有,我要限定一个50位长度的字符串,那岂不是得把[A-Z]复制50次?请大家帮帮忙,谢谢

------解决方案--------------------
constraint ck_col1 check(patindex('%[^a-zA-Z]%',col1)=0)
------解决方案--------------------
以check前3位均为字母为例,
SQL code

create table rai
( id int identity(1,1),
  pn varchar(10) constraint ck_rai_pn 
                 check(patindex('%[^A-Z]%',left(pn,3))=0 
                       or patindex('%[^A-Z]%',left(pn,3))>3)
)

insert into rai(pn) values('DR1')

/*
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "ck_rai_pn". The conflict occurred in database "DBAP", table "dbo.rai", column 'pn'.
The statement has been terminated.
*/

insert into rai(pn) values('DRS')
insert into rai(pn) values('DRSP')

select * from rai

/*
id          pn
----------- ----------
2           DRS
3           DRSP

(2 row(s) affected)
*/