表a,表b
表a结构
id name 
1  a
2  b
3  c
4  d
表b结构
id name 
1  a    
2  b    要实现的功能是:判断表a的id和表b的id两者是否相等,如果不相等,就把表a的当前记录插入到表b里,如果相等则继续判断,表a里有4条记录而表b只有2条记录,那就把表a比表b多的记录插入到表b里,执行后的结果就是表a的记录和表b的记录个数相等,结果:
表a结构
id name 
1  a
2  b
3  c
4  d
表b结构
id name 
1  a    
2  b
3  c
4  d我用的asp.net(c#)开发的

解决方案 »

  1.   


    insert into b select * from a where not exists(select 1 from b where id=a.id and name=a.name)
      

  2.   

    insert into b select * from A where id not (select id from b)
      

  3.   

    insert into b select * from a where not exists(select 1 from b where id=a.id and name=a.name)
    insert into b select * from A where id not in(select id from b)
    少个in
      

  4.   

    create table A(id int, name varchar(10))
    insert into A values(1, 'a') 
    insert into A values(2, 'b') 
    insert into A values(3, 'c') 
    insert into A values(4, 'd') 
    create table B(id int, name varchar(10))
    insert into B values(1, 'a') 
    insert into B values(2, 'b') 
    go--如果只考虑id
    insert into b select * from A where id not in (select id from b)
    select * from B
    /*
    id          name       
    ----------- ---------- 
    1           a
    2           b
    3           c
    4           d
    (所影响的行数为 4 行)
    */--考虑id,name
    insert into b select * from A where not exists (select 1 from b where id = a.id and name = b.name)
    select * from B
    /*
    id          name       
    ----------- ---------- 
    1           a
    2           b
    3           c
    4           d
    (所影响的行数为 4 行)
    */drop table A,B