如何比较 SQL 服务器中的两行

How to comapre two rows in SQL Server

考虑 table

中的以下行
ID  | Fname  | Lname   | Age | Weight 
-----------------------------------
23  | Kareem | Benzema | 30  | 75
24  | Karim  | Benzema | 32  | 75

我想比较两行并找出它们之间的差异。 我需要的结果是:

ColumnName | OldValue | NewValue
---------------------------------
ID         | 23       | 24
---------------------------------
Fname      | Kareem   | Karim
---------------------------------
Age        | 30       | 32 

嗯。 . .让我假设您的值都是字符串,因为它们将存储在一列中。然后使用 apply 反转并使用 lag():

select v.columnName,
       lag(v.value) over (partition by v.columnName order by t.id) as oldValue,
       v.value as newValue
from t cross apply
     (values ('id', t.id),
              ('fname', t.vname),
              ('lname', t.lname),
              ('age', t.age),
              ('weight', t.weight)
     ) v(ColumnName, Value);

最后,您只需要更改,所以使用子查询:

select v.*
from (select v.columnName,
             lag(v.value) over (partition by v.columnName order by t.id) as oldValue,
             v.value as newValue
      from t cross apply
           (values ('id', t.id),
                   ('fname', t.vname),
                   ('lname', t.lname),
                   ('age', t.age),
                   ('weight', t.weight)
           ) v(ColumnName, Value);
      ) v
where oldvalue <> newvalue;

...调整..

declare @t table(ID int, Fname varchar(50), Lname varchar(50), Age tinyint, Weight smallint);

insert into @t(ID, Fname, Lname, Age, Weight)
values
(23, 'Kareem', 'Benzema', 30, null),
(24, 'Karim', 'Benzema', 32, 75);


select r1.[key], r1.value as oldvalue, r2.value as newvalue
from
(
    select 
        max(case when dt.rownum=1 then dt.thejson end) as row1,
        max(case when dt.rownum=2 then dt.thejson end) as row2
    from
    (   
        select 
            row_number() over(order by /*ID ?*/ @@spid) as rownum,
            (select t.* for json path, include_null_values, without_array_wrapper) thejson
        from @t as t
        where ID in (23, 24)--input
    ) as dt
) as src
cross apply openjson(src.row1) as r1
cross apply openjson(src.row2) as r2
where r1.[key] = r2.[key]
and (r1.value <> r2.value or r1.type <> r2.type) --type for null?
;