有A、B两个表,A、B表结构不相同...A表结构(id自增、code(varchar(50))、state(bit)),B表结构(id自增、code(varchar(50)))...我想把B表中code字段的数据插入到A表中(注意:B表中code字段中有的数据可能跟A表中的数据相同,我想把B表与A表不同的数据插入到A表中)如下所示:A 表
id code state
1   aa    0
2   bb    0B 表
id code
1   aa
2   dd两个表比较之后我把B表中的 dd 插入到A表中结果如下:A 表
id code state
1   aa    0
2   bb    0
3   dd    0
求这样的SQL insert 语句....

解决方案 »

  1.   


    insert into a
    select code,0 as state 
    from b t 
    where not exists (select 1 from a where code = t.code)
      

  2.   

    create table ta(id int identity(1,1),code varchar(10), state int)
    insert into ta select 'aa',0
    insert into ta select 'bb',0
    create table tb(id int identity(1,1),code varchar(10))
    insert into tb select 'aa'
    insert into tb select 'dd'
    go
    insert into ta select code,0 from tb a where not exists(select 1 from ta where code=a.code)
    select * from ta
    /*
    id          code       state
    ----------- ---------- -----------
    1           aa         0
    2           bb         0
    3           dd         0(3 行受影响)*/
    go
    drop table tb,ta
      

  3.   

    insert a(code,state)
    select code,state from b where b.code not in (select code from a)