两个表
sy1:
id  grade
1  30
2  20
3  30
4  20sy2:
id grade
1  60
2  60
5  90
6  90怎么样把sy2表的grade更新到sy1表上,并且不能把sy1表的id为3 和4 的grade保持不变?
下面的语句会把id为3 和4 的grade置为空值
update sy1 a set grade=
(select b.grade from sy2 where b.id=a.id)

解决方案 »

  1.   

    merge into  a
    using (select id,name from b ) c
    on(a.id=c.id )
    when matched then update set a.name=c.name
    when not matched then insert (a.id,a.name) values (c.id,c.name);
    作用:将表 b 数据 更新到 表a ,条件是a.id=b.id,如果a表中有该条件的数据就修改,没有该条件的数据就插入。如果你的数据量很大,此sql效率非常高。 
      

  2.   

    update sy1 a set grade= 
    (select b.grade from sy2 b where b.id=a.id) where
    exists (select 1 from sy2 c where c.id=a.id)
      

  3.   

    update sy1 a set grade = (select b.grade from sy2 b where b.id=a.id) 
    where exists (select 1 from sy2 b where a.id=b.id);
      

  4.   

    你需要把sy2的5和6 insert到sy1吗?
      

  5.   

    非常感谢,那个1要改成*
    update sy1 a set grade= 
    (select b.grade from sy2 b where b.id=a.id) where 
    exists (select * from sy2 c where c.id=a.id)
      

  6.   

    呵呵...1比*更好,数据量大的时候你就可以看到performance的区别的.