如何比较 SQL 服务器中 2 个不同表中单元格中的数据?

How to compare data in cells in 2 different tables in SQL Server?

我有 2 个相同的 table。在其中一个 table 中,任何行中单元格的值都可以更改,另一个 table 是不变的。如何找出哪一行的哪个值发生了变化?

例如,我有 Table1(屏幕截图 #1)和 Table2(屏幕截图 #2),其中任何行中任何单元格的值都可以更改。我想检测变化并知道它变成了什么值。 table 中的行数和列数将保持不变。

如何比较下面屏幕截图中显示的这 2 个 table 以找出差异?

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

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