SQL新手问CHECK约束的问题

PackChen 2010-09-22 02:46:46
表Country(ID,Code,Name)国家
表City(ID,Code,Name)城市
表Persion(ID,Code,Name,Country,City)人员

三张表都是NOT NUL的

主键都是ID(自增),但是三张表的Code都显式建立了Unique Index索引

要求Persion.Country这个字段必须来自Country表的数据
要求Persion.City这个字段要么等于空串,要么必须匹配City.Code

请问SQL 的CHECK如何编写
...全文
83 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
PackChen 2010-09-22
  • 打赏
  • 举报
回复
对xman_78tom这位兄弟表示感谢
如果是null的话是可以的,但是如果是空串''就不行
但是依然感谢
结贴,给分
xman_78tom 2010-09-22
  • 打赏
  • 举报
回复
#4楼 的语句在 sql server 2008 中成功执行,没有“违反约束”的错误。
PackChen 2010-09-22
  • 打赏
  • 举报
回复
上面的错误贴错了

如果person.city_code不等于city.code,那么就必须是null,而不是空串,区别在这里
但是在程序处理null很麻烦
等会结贴
PackChen 2010-09-22
  • 打赏
  • 举报
回复
谢谢楼上的,不过楼上的明显有错误

insert into person (code, name,country_code,city_code)
values ('000100010001','Hu','0001',null);

执行到此句时肯定是不行的

INSERT 语句与 COLUMN FOREIGN KEY 约束 'FK__person__country___79A81403' 冲突。该冲突发生于数据库 'tempdb',表 'country', column 'code'。
语句已终止。

因为三个表的所有字段都不能出现null,所以无法用外键约束,看来是没法解决了
不过还要是感谢楼上的
xman_78tom 2010-09-22
  • 打赏
  • 举报
回复
foreign key 约束不就是这样?person.city_code 可以为 null,如果不为空则必须匹配 city.code。
难道非要举个例子,

create table country (id int identity, code char(4) not null, name varchar(40) not null);
create unique index ix_country_code on country(code);
go
insert into country(code, name) values('0001','China');
go

create table city (id int identity, code char(8) not null, name varchar(40) not null);
create unique index ix_city_code on city(code);
go
insert into city (code,name) values('00010001','Beijin');
go

create table person
(id int identity, code char(12) not null, name varchar(40) not null,
country_code char(4) references country(code),
city_code char(8) references city(code));
create unique index ix_person_code on person(code);
go
insert into person (code, name,country_code,city_code)
values ('000100010001','Hu','0001',null);
go

select * from person;
/*
1 000100010001 Hu 0001 null
*/
update person set city_code='00010001' where id=1;

select * from person;
/*
1 000100010001 Hu 0001 00010001
*/
drop table person,country,city;
go
rucypli 2010-09-22
  • 打赏
  • 举报
回复
ID是唯一的 有必要要code吗
PackChen 2010-09-22
  • 打赏
  • 举报
回复
谢谢楼上的
但是对于city的约束失败,
因为实际情况上,persion.city可以不填,如果填写了就必须匹配city.code

就是说,persion.city要么是空,要么就必须是city表里面的
xman_78tom 2010-09-22
  • 打赏
  • 举报
回复
这个需要使用“外键”约束。

create table country (id int identity, code char(4) not null, name varchar(40) not null);
create unique index ix_country_code on country(code);

create table city (id int identity, code char(8) not null, name varchar(40) not null);
create unique index ix_city_code on city(code);

create table person
(id int identity, code char(12) not null, name varchar(40) not null,
country_code char(4) references country(code),
city_code char(8) references city(code));
create unique index ix_person_code on person(code);

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧