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

比较两表并去重
现有两表t1,t2(表结构一样),t1为临时表,t2为最终表。
需要比较两个表t1,t2的数据,如果t2已有数据和t1相同,则不插入到t2,否则把t1中的数据插入到表t2。
怎么写?多多赐教!

------解决方案--------------------
SQL code

insert t2
select * from t1 b
where not exists(select 1 from t2 a where a.col1=b.col1 
and a.col2=b.col2.......)

------解决方案--------------------
SQL code


insert into t2
select * from t1 left join t2 on t1.关联字段=t2.关联字段
where  t2.关联字段 is null

------解决方案--------------------
如果是MSSQL2008及以上版本,可以使用Merge语句:
merge into t2 a
using t1 b
on a.col1=b.col1
when not matched then --当目标表中没有来源表的记录的时候,就添加
insert (col1,col2,col3,col4,...)
values (b.col1,b.col2,b.col3,b.col4,...)

Merge语句优缺点:
优点:不需要访问数据多次,而且作为原子操作进行处理的,不用显示声明事务。
缺点:按照完整方式记录日志。

------解决方案--------------------
2005及以上版本可以用
ETC