+ -
当前位置:首页 → 问答吧 → 请问一个约束的问题?

请问一个约束的问题?

时间:2011-12-01

来源:互联网

如果有一个char(11)的字段,如果想约束其数据:使其出现的字符只能是0-9之中一个,怎么做呀?是用正则表达式吗?

作者: chp845   发布时间: 2011-12-01

SQL code

if object_id('tb','U') is not null
   drop table tb
go
create table tb
(
 id int,
 age int check(age>0 and age<9)
)
go
insert into tb select 1,2

作者: pengxuan   发布时间: 2011-12-01

SQL code

--改一下
if object_id('tb','U') is not null
   drop table tb
go
create table tb
(
 id int,
 age int check(age>=0 and age<=9)  应该是>=0 and <=9
)
go
insert into tb select 1,2


作者: pengxuan   发布时间: 2011-12-01

SQL code

create table t1
(
    col1 char(11) check (col1 like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
)

作者: gogodiy   发布时间: 2011-12-01

SQL code
create table tb(id char(11) check (PATINDEX('%[^0-9]%',id) =0) )
go

insert into tb values('0102ad')

select * From tb

drop table tb

/*
INSERT 语句与 COLUMN CHECK 约束 'CK__tb__id__4A4E069C' 冲突。该冲突发生于数据库 'pubs',表 'tb', column 'id'。
语句已终止。
id          
----------- 

(所影响的行数为 0 行)
*/

作者: dawugui   发布时间: 2011-12-01

SQL code
alter table tb
add constraint ck_test check(col1 like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
go

作者: fredrickhu   发布时间: 2011-12-01


抢楼抢得挺快,1、2楼的全是错的

作者: pengxuan   发布时间: 2011-12-01

引用 3 楼 gogodiy 的回复:
SQL code


create table t1
(
col1 char(11) check (col1 like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
)

正解

作者: wang7535067   发布时间: 2011-12-01