j_t*_*ion 8 sql check-constraints sql-server-2008-r2
我创建了一个名为testwith column 的表code:
create table test(
code char(3) not null);
Run Code Online (Sandbox Code Playgroud)
然后我用以下数据填充表格:
insert into test values ('A12');
insert into test values ('B23');
insert into test values ('C45');
Run Code Online (Sandbox Code Playgroud)
然后我改变了列以使其成为char(4):
alter table test
alter column code char(4) not null;
Run Code Online (Sandbox Code Playgroud)
然后我为所有现有数据添加了一个"X",使其变为4个字符长:
update test
set code='X'+code
where LEN(code)=3;
Run Code Online (Sandbox Code Playgroud)
到目前为止这么好但是当我尝试添加检查约束时:
alter table test
add constraint codeCheck check (code like 'A-Z''A-Z''0-9''0-9');
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误:
The ALTER TABLE statement conflicted with the CHECK constraint "codeCheck".
我理解错误意味着现有数据违反了我试图添加到表中的检查约束,但为什么呢?
我该怎么做才能使现有数据和检查约束不相互冲突?
Mar*_*ith 16
您的模式语法错误.它应该是
alter table test
add constraint codeCheck check (code like '[A-Z][A-Z][0-9][0-9]');
Run Code Online (Sandbox Code Playgroud)