Compare two rows and identify columns whose values are different

后端 未结 4 2107
忘了有多久
忘了有多久 2020-12-17 23:20

The Situation

We have an application where we store machine settings in a SQL table. When the user changes a parameter of the machine, we create a \

4条回答
  •  -上瘾入骨i
    2020-12-17 23:58

    Here's one way using UNPIVOT:

    ;WITH
        cte AS
        (
            SELECT      CASE WHEN t1.p_x <> t2.p_x THEN 1 ELSE 0 END As p_x,
                        CASE WHEN t1.p_y <> t2.p_y THEN 1 ELSE 0 END As p_y,
                        CASE WHEN t1.p_z <> t2.p_z THEN 1 ELSE 0 END As p_z
            FROM        MyTable t1, MyTable t2
            WHERE       t1.ID = 11 AND t2.ID = 12 -- enter the two revisions to compare here
        )
    
    SELECT      *
    FROM        cte
    UNPIVOT     (
                    Changed FOR ColumnName IN (p_x, p_y, p_z)
                ) upvt
    WHERE       upvt.Changed = 1
    

    You have to add code to handle NULLs during the comparisons. You can also build the query dynamically if there are lots of columns in your table.

提交回复
热议问题