求A表向B表的复制SQL语句
如题,A表和B表结构相同如下
ID,NAME,CASE,UPDDATE
ID和NAME为主键,复制过程中,
1.A表中的记录如果在B表中有相同主KEY的话,就比较UPDDATE(更新日期),如大于B表的更新日期,就做更新处理(更新除主KEY以外所有的字段),否则不做处理
2.如果不存在,就插入B表
A表
001,NAME1,CASE1,20070903(更新处理)
002,NAME2,CASE2,20070906(插入处理)
003,NAME3,CASE3,20070405(不做处理)
........
B表
001,NAME1,00000,20070901
003,NAME3,CASE3,20070909
........
最后结果为
B表
001,NAME1,CASE1,20070903
002,NAME2,CASE2,20070906
003,NAME3,CASE3,20070909
........
------解决方案--------------------1、update
update b
set case = a.case,
upddate = a.upddate
from b,a
where b.id = a.id and b.name = a.name and b.upddate < a.upddate
2、insert
insert into b select * from a where cast(a.id as varchar) + cast(a.name as varchar) not in (select cast(a.id as varchar) + cast(a.name as varchar) from b)
------解决方案--------------------insert into B
select A.* from A left join B on A.ID=B.ID where A.UPDDATE> B.UPDDATE or B.month is null;