日期:2014-05-18  浏览次数:20732 次

SQL语句实现:将表1更新到表2,更新条件为存在则更新,否则添加。
如:表Table1、Table2,表结构一样都有A、B两个字段,A字段值不重复。

需求:
对于Table2中的每一条记录,都要判断Table1中是否存在某一记录和它相同(即:A字段值相同),如果相同则更新Table1中该记录使Table1.B=Table2.B,否则将Table2的这条记录插入到Table1中。

当然要追求效率了,多谢。

------解决方案--------------------
update table1 set B=Table2.B from table2 where table1.A=table2.A

insert into table1
select * from table2 where not exists(select 1 from table1 where A=table2.A)
------解决方案--------------------
update Table1
set B=Table2.B
from Table1,Table2
where Table1.A=Table2.A

insert into Table1
select *
from Table2 a where not exists(select 1 from Table1 b where a.A=b.A)
------解决方案--------------------
update table1 set B=t2.B
from table1 as t1 inner join table2 as t2 on t1.A=t2.A

insert into table1
select *
from table2
where A not in (select A from table1)