首页 > 解决方案 > 如何比较 SQL Server 中 2 个不同表中的单元格中的数据?

问题描述

我有两张相同的桌子。在其中一个表中,任何行中单元格的值都可以更改,而另一个表是恒定的。如何找出哪一行中的哪个值发生了变化?

例如,我有Table1(screenshot #1) 是恒定的,而Table2(screenshot #2) 任何行中任何单元格的值都可以更改。我想检测更改并知道它更改为什么值。两个表中的行数和列数将保持不变。

如何比较这两个表,如下面的屏幕截图所示,以找出差异?

图片1

图片2

标签: sql-serversql-server-2008

解决方案


一种方法可能是 UNPIVOT 两个表,然后内部 JOIN。在这种情况下,我将 #tempA 中 row=3, col='a' 的值从 111 更改为 11。查询返回任何差异

drop table if exists #tempA;
go
create table #tempA(
  a      int not null,
  b      int not null,
  c      int not null);

insert #tempA values
(1, 2, 3),
(11, 22, 33),
(11, 222, 333);

drop table if exists #tempB;
go
create table #tempB(
  a      int not null,
  b      int not null,
  c      int not null);

insert #tempB values
(1, 2, 3),
(11, 22, 33),
(111, 222, 333);

with
a_cte(a, b, c, rn) as (
    select *, row_number() over (order by a) 
    from #tempA),
b_cte(a, b, c, rn) as (
    select *, row_number() over (order by a) 
    from #tempB),
a_unpvt_cte as (
    select v.* 
    from a_cte a
         cross apply (values ('a', a, rn), ('b', b, rn), ('c', c, rn)) v(col, letter, rn)),
b_unpvt_cte as (
    select v.* 
    from b_cte a
         cross apply (values ('a', a, rn), ('b', b, rn), ('c', c, rn)) v(col, letter, rn))
select a.col, a.rn, a.letter a_letter, b.letter b_letter
from a_unpvt_cte a
     join b_unpvt_cte b on a.col=b.col
                           and a.rn=b.rn
where
  a.letter<>b.letter;
col rn  a_letter    b_letter
a   3   11          111

推荐阅读