在SQL中比较两个具有不同字段名称的表

时间:2011-04-24 05:47:37

标签: sql

比较两个表中具有相同主键的2个不同表中的数据值的最佳方法是什么?

有人能建议最好的方法吗?

3 个答案:

答案 0 :(得分:3)

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

  1. 您可以在一个表中包含另一个表中不存在的行。在这里,您需要在一侧对每个表进行两次左连接查询。

  2. 对于共同的记录,您需要逐个比较这些字段。不幸的是,简单的方法。另一种方法是在整行上进行校验和。

  3. 您还可以购买sql redgate比较和数据比较,它比较结构和数据。您可以尝试使用试用版软件 - 它非常棒。

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

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

答案 1 :(得分: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
        ...

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

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

答案 2 :(得分: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)

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

编辑 - 你对不同的字段名称是什么意思?如果两个表都有不同的字段,那么它们当然不同......