gpt4 book ai didi

sql - 将CHECK约束添加到已填充的表中

转载 作者:行者123 更新时间:2023-12-04 05:25:13 24 4
gpt4 key购买 nike

我创建了一个名为test的表,其表名为code:

create table test(  
code char(3) not null);

然后,我用以下数据填充表:
insert into test values ('A12');
insert into test values ('B23');
insert into test values ('C45');

然后,我将列更改为char(4):
alter table test
alter column code char(4) not null;

然后,我向所有现有数据添加了“X”,使其变为4个字符长:
update test
set code='X'+code
where LEN(code)=3;

到目前为止一切顺利,但是当我尝试添加检查约束时:
alter table test
add constraint codeCheck check (code like 'A-Z''A-Z''0-9''0-9');

我收到此错误:
The ALTER TABLE statement conflicted with the CHECK constraint "codeCheck".
我知道该错误表示现有数据违反了我要添加到表中的检查约束,但是为什么呢?

以及如何使现有数据和检查约束互不冲突?

最佳答案

您的模式语法错误。它应该是

alter table test
add constraint codeCheck check (code like '[A-Z][A-Z][0-9][0-9]');

关于sql - 将CHECK约束添加到已填充的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12621824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com