两个表,有不是自动增加的id字段,一个表会增加记录,要更新另一个表,就是把这些记录加到另一个表,已经加入的不修改,要怎么写sql语句?

解决方案 »

  1.   

    insert into tb2(id) select * from tb1 where id not in (select id from tb2)
      

  2.   

    使用触发器
    create trigger t1
    on tb1
    for insert
    insert into t2
    select * from inserted where not exists(select 1 from tb2 where tb2.id=t2.id)
      

  3.   

    INSERT TB(字段列表) SELECT 字段列表 FROM TA WHERE ID NOT IN(SELECT ID FROM TB)
      

  4.   

    如果是每次都这么写,需要使用触发器.CREATE TRIGGER my_trig ON tb1 FOR INSERT
    as
      insert into tb2 select id from inserted where id not in (select id from tb2)
    go
      

  5.   

    如果要将数值加入到自增字段中,可将自增功能先停止,插入后再开启set identity_insert TableName on 
    insert tablename(字段1,字段2...) select 字段1,字段2... from YuanTable --必须指定列名
    set identity_insert TableName off 
    ========================================
    http://www.dbtuning.cn
    主营:中小企业数据库管理、优化、调校服务
    ========================================
      

  6.   

    前提是两个表结构相同
    insert into tb2 select * from tb1 where id not in(select id from tb1)
      

  7.   

    insert into tb2(id,col1,col2)
    select * from tb1 t
    where not exists(
    select * from tb2 where id=t.id
    )