如题:求一个mobile字段的约束,既可以为空值,或者 null值   如果有值的话,这个字段必须是在这个表中 唯一存在的 求 约束 表达式 代码。

解决方案 »

  1.   

    使用带条件的唯一索引 。
    给你写一个示例
    create table test(id int identity,name varchar(10))
    go
    create unique index test_ix on test(name) where (name is not null) and (name != '')
    go
    insert into test values('a')
    insert into test values('a')
    insert into test values(null)
    insert into test values(null)
    insert into test values('')
    insert into test values('')
    go
    select * from test 
    go
    drop table test 
    go
    (1 行受影响)
    消息 2601,级别 14,状态 1,第 2 行
    不能在具有唯一索引 'test_ix' 的对象 'dbo.test' 中插入重复键的行。
    语句已终止。(1 行受影响)(1 行受影响)(1 行受影响)(1 行受影响)
    id          name
    ----------- ----------
    1           a
    3           NULL
    4           NULL
    5           
    6           (5 行受影响)