比较两行并显示列名和更改数据的差异


Compare 2 rows and show differences with column name and changed data

我们有两个相同结构的表(MSSQL)我们想要比较(ID) 122从表1与from table

如果存在一个或多个差异,我们希望显示列名以及它保存的两个表中的数据。

我不想列出所有的列,因为有超过150个

类似于(psuedo): -

Select * from table1 
Select * from table2
Compare table1 (column by column) with table2 (column by column)

显示更改:-

'Name' WAS 'John' NOW 'James' CHANGED 3/11/2016 3.45pm'Mobilenum ' WAS '02373643743' NOW '0983783738' CHANGED 4/11/2016 12.46pm

不要尝试触发器…需要PHP代码....我们不需要给出任何列名,因为它应该动态地运行它们…

为什么不列出列-这个表会定期更改吗?您仍然可以动态创建SQL—但是将其存储为静态字符串。有很多这样的例子(提示使用information_schema.columns)如果表不是很大,那么我会写一堆测试(每列1个)和UNION所有它们在一起-然后只返回diff = true的数据如

    Select * from 
    (
    Select case when ISNULL(table1.columnA, -999) <>  ISNULL(table2.columnA, -999) then 1 else 0 end as diff, table1.columna as Old_Val, table2.columnA as new_val
    from table1 join table2 on ...
    UNION ALL
    /* etc etc * 150 ... */
    ) as x
where x.diff = 1