数据是这样的:
a  b
1  1001
1  1002
2  1002
3  1003
但是不允许插入与ab两字段已有数据都相同的数据(1 1001不允许,4 1001允许),sql语句应该怎么写?

解决方案 »

  1.   

    insert tab (a,b)
    select a=1,b=1001 where not exists (select 1 from tab where a=1)
      

  2.   

    上面语句因为有重复而不插入下面语句可以插入insert tab (a,b)
    select a=4,b=1001 where not exists (select 1 from tab where a=4)
      

  3.   

    或者这么写if not exists (select 1 from tab where a=1)
    insert tab (a,b)
    values( 1,1001)
      

  4.   

    if not exists(select * from table where a=2 and b=1001)
      insert into table values (1,1001)
      

  5.   

    if not exists(select * from table where a=2 and b=1001)
      insert into table values (2,1001)
      

  6.   


    if object_id('tb') is not null
       drop table tb
    go
    create table tb(a int,b int)
    go
    insert into tb
    select 1,1001 union all
    select 2,1002 union all
    select 3,1002 union all
    select 4,1003
    go
    insert into tb select 1,1001 where not exists(select 1 from tb where a=1 and b=1001)
    insert into tb select 1,1001 where not exists(select 1 from tb where a=4 and b=1001)select * from tb
      

  7.   

    if not exists(select * from table where a=2 and b=1001)
      insert into table values (2,1001)
      

  8.   

    另外建立触发器:
    create trigger t1
    on tb
    for insert
    as
    if exists(select 1 from tb,inserted where tb.a=inserted.a and tb.b=inserted.b)
       rollback