如何建立这样的约束:允许多个null值;如果不是null值,就必须是唯一的,不许重复。也就是可以重复null值,其他值不允许重复。在sql2005里面,这样的约束怎么设置?

解决方案 »

  1.   

    那只允许1个null,现在要允许多个null,怎么办?
      

  2.   

    --这样?
    create table a(a int)
    gocreate trigger cfq on a
    instead of insert
    asif @@rowcount=0 returnif(select 1 from inserted where a is NULL)=1
     begin
      insert into a select NULL from inserted where a is NULL
     end
    else
     begin
       if exists(select 1 from a,inserted b where a.a=b.a)
         begin
           raiserror('存在相同记录!',16,1)
           rollback tran
         end
       else
         begin
           insert into a select * from inserted where a is not NULL
         end
     end
    goinsert into a select 1
    select * from a
    goinsert into a select NULL
    insert into a select 1drop trigger cfq
    drop table a
      

  3.   

    create table a(a int)
    gocreate trigger cfq on a
    instead of insert
    asif @@rowcount=0 returninsert into a select NULL from inserted where a is NULLif exists(select 1 from a,inserted b where a.a=b.a)
     begin
       raiserror('存在相同记录!',16,1)
       rollback tran
     end
    else
     begin
       insert into a select * from inserted where a is not NULL
     end
    goinsert into a select 1
    select * from a
    goinsert into a select NULL
    insert into a select 1drop trigger cfq
    drop table a
      

  4.   

    set nocount on
    create table a(a int)
    gocreate trigger cfq on a
    instead of insert
    asif @@rowcount=0 returnif exists(select 1 from a,inserted b where a.a=b.a and a.a is not NULL)
     begin
       raiserror('存在相同记录!',16,1)
     endinsert into a select NULL from inserted where a is NULL
    insert into a select * from inserted where a is not NULL and not exists(select 1 from a,inserted b where a.a=b.a)
    goinsert into a select 1
    select * from a
    goinsert into a select NULL
    insert into a select 1
    insert into a select NULL
    insert into a select 2
    insert into a select NULL
    insert into a select 2
    drop trigger cfq
    drop table a