表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如何编写

解决方案 »

  1.   

    这个需要使用“外键”约束。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);
      

  2.   

    谢谢楼上的
    但是对于city的约束失败,
    因为实际情况上,persion.city可以不填,如果填写了就必须匹配city.code就是说,persion.city要么是空,要么就必须是city表里面的
      

  3.   

    ID是唯一的 有必要要code吗
      

  4.   

    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');
    gocreate 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');
    gocreate 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);
    goselect * 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
      

  5.   

    谢谢楼上的,不过楼上的明显有错误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,所以无法用外键约束,看来是没法解决了
    不过还要是感谢楼上的
      

  6.   

    上面的错误贴错了如果person.city_code不等于city.code,那么就必须是null,而不是空串,区别在这里
    但是在程序处理null很麻烦
    等会结贴
      

  7.   

    #4楼 的语句在 sql server 2008 中成功执行,没有“违反约束”的错误。
      

  8.   

    对xman_78tom这位兄弟表示感谢
    如果是null的话是可以的,但是如果是空串''就不行
    但是依然感谢
    结贴,给分