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

求一简单查询语句(查询两个不同数据库中有相同一表结构的不同数据)
在两个不同数据库中,都有同一表结构的表,如果能查到这两个相同表结构不同的数据呢?
如:有数据库   a   ,b
    数据库a中有表table1,数据库b中有表table2,table1和table2表结构相同,怎么查出table1和table2不同的数据

------解决方案--------------------
---- 是这样么?
select * from a.dbo.table1 where not exists (select * from b.dbo.table2)
union
select * from b.dbo.table2 where not exists (select * from a.dbo.table1)
------解决方案--------------------
怎么查出table1和table2不同的数据
====
--假设两数据库在同一机器上
--1先查a数据库多出的记录
select * from a.dbo.table1 t1 where not exists
(select 1 from b.dbo.table2 t2 where t2.主键=t1.主键)
--2再查b数据库多出的记录
select * from b.dbo.table1 t1 where not exists
(select 1 from a.dbo.table2 t2 where t2.主键=t1.主键)

------解决方案--------------------
用checksum()函数。

--A中不在B中的。
select *
from A
where checksum(*) not in (select checksum(*) from B)


--B中不在A中的。
select *
from B
where checksum(*) not in (select checksum(*) from A)


--A中不在B中的 + B中不在A中的。
select *
from A
where checksum(*) not in (select checksum(*) from B)
union
select *
from B
where checksum(*) not in (select checksum(*) from A)