2011-04-24 267 views
0

在两个表中具有相同主键的两个不同表中比较数据值的最佳方法是什么?比较SQL中具有不同字段名称的两个表

任何人都可以提出最好的方法吗?

+1

请更具体一些。你想要比较多少列?提供表格模式也有帮助。 – harpo 2011-04-24 05:49:34

+1

比较以什么方式?你想达到什么目的? – Oded 2011-04-24 05:50:54

+0

这两个表的数据类型是否相同? – 2011-04-24 05:51:24

回答

3

如果要比较数据值,则有两个级别;

  1. 您可以在一个表中存在不存在于另一个表中的行。在这里,您需要在一边对每个表执行两个左连接查询。

  2. 对于相同的记录,您需要逐个比较字段。不幸的是,很容易。另一种方法是在整行上执行校验和。

您还可以购买sql redgate比较和数据比较,比较结构和数据。你可以试用它的试用软件 - 它真棒。

http://www.red-gate.com/products/sql-development/sql-compare/

http://www.red-gate.com/products/sql-development/sql-data-compare/

1

通常的办法比较两个表是full outer join,如:

select coalesce(t1.pk, t2.pk) as Key 
,  case 
     when t1.pk is null then 'Not found in Table1' 
     when t2.pk is null then 'Not found in Table2' 
     else 'Different' 
     end as Reason 
from Table1 as t1 
full outer join 
     Table2 as t2 
on  t1.pk = t2.pk 
where t1.pl is null 
     or t2.pk1 is null 
     or t1.col1 <> t2.col1 
     or t1.col2 <> t2.col2 
     or t1.col3 <> t2.col3 
     ... 

空列需要额外的逻辑。假设没有行包含值<<NULL>>,你可以:

 or IsNull(t1.col4,'<<NULL>>') <> IsNull(t2.col4,'<<NULL>>') 
0

与BINARY_CHECKSUM功能,像这样尝试:

declare @Table1 table (Id int identity(1,1), Param1 varchar(10), Param2 int) 
declare @Table2 table (Id int identity(1,1), Param1 varchar(10), Param2 int) 

insert into @Table1 (Param1, Param2) select 'A', 1 
insert into @Table2 (Param1, Param2) select 'A', 1 

select t1.*, t2.* 
from @Table1 t1 full join @Table2 t2 on (t1.Id = t2.Id) 
where binary_checksum(t1.Id, t1.Param1, t1.Param2) <> binary_checksum(t2.Id, t2.Param1, t2.Param2) 

查询返回的记录,那只是一个表中,而不是在另一。该查询还返回两个表(使用主键)中的记录,但其他列是不同的。

编辑 - 你是什么意思与不同的字段名称?如果两个表格都有不同的字段,那么它们的偏差就会不同...

相关问题