比如create table City
(
CityId int primary key,
CityName varchar(80) not null
)create table User
(
UserId int primary key,
CityId int null references City(CityId) on delete set null
)
我不想让User里的CityId为null,
而是当不存在是指定为0,能做到吗?谢谢了~

解决方案 »

  1.   

    on delete set 0有语法错误?
    on delete set null 没有。
    怎么办?
      

  2.   

    木必要非把null 换成 0 吧
      

  3.   

    很多人说null在数据库里很令人讨厌啊。
      

  4.   

    create table City
    (
    CityId int primary key,
    CityName varchar(80) not null
    )create table [User]
    (
    UserId int primary key,
    CityId int null references City(CityId) on delete set null
    )
    insert into city select 0,'未定'
    go
    insert into [user] select 1,0
    go
    select a.userid,b.cityname from [user] a inner join city b on a.cityid=b.cityid
    /*
    userid      cityname
    ----------- --------------------------------------------------------------------------------
    1           未定(1 行受影响)*/
    go
    drop table [user]
    drop table city
      

  5.   

    SET NULL 
    如果父表中对应的行被删除,则组成外键的所有值都将设置为 NULL。若要执行此约束,外键列必须可为空值。这个设置是当主键表中的某行删除时,级联更新从表外键为NULL,其实这个设置很少用的.一般的级联都是从表有值时,主表不允许删除.如果你一定要在允许从表与主表不存在连接,而且还要数据库自行检验的话,可以先用 set null,而后用一条更新语句将该列的NULL更新为0.
    其实,外键被你用到这种地步,还不如不加外键,直接在业务层中按你的要求来保证参照完整性呢.
      

  6.   

    CityId int default 1  references City(CityId) on delete set default