I need to add table called group
with a column called code
我需要添加一个名为group的表,其中包含一个名为code的列
How do I add a check constraint to the column so it will only allow the following alphabetic characters (D, M, O, P or T) followed by 2 numeric characters.
如何向列添加检查约束,以便它只允许以下字母字符(D,M,O,P或T)后跟2个数字字符。
1 个解决方案
#1
simple check constraint is all you need
简单的检查约束就是你所需要的
create table blatest(code char(3))
alter table blatest add constraint ck_bla
check (code like '[DMOPT][0-9][0-9]' )
GO
test
insert blatest values('a12') --fails
insert blatest values('M12') --good
insert blatest values('D12') --good
insert blatest values('DA1') --fails
If you need it to be case sensitive then you have to create the constraint like this
如果您需要它区分大小写,那么您必须创建这样的约束
alter table blatest add constraint ck_bla
check (code like '[DMOPT][0-9][0-9]' COLLATE SQL_Latin1_General_CP1_CS_AS )
GO
D12 will succeed but d12 will not in that case
D12会成功,但在这种情况下d12不会
#1
simple check constraint is all you need
简单的检查约束就是你所需要的
create table blatest(code char(3))
alter table blatest add constraint ck_bla
check (code like '[DMOPT][0-9][0-9]' )
GO
test
insert blatest values('a12') --fails
insert blatest values('M12') --good
insert blatest values('D12') --good
insert blatest values('DA1') --fails
If you need it to be case sensitive then you have to create the constraint like this
如果您需要它区分大小写,那么您必须创建这样的约束
alter table blatest add constraint ck_bla
check (code like '[DMOPT][0-9][0-9]' COLLATE SQL_Latin1_General_CP1_CS_AS )
GO
D12 will succeed but d12 will not in that case
D12会成功,但在这种情况下d12不会