Compare two rows and identify columns whose values are different

后端 未结 4 2108
忘了有多久
忘了有多久 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条回答
  •  时光取名叫无心
    2020-12-17 23:45

    You can use unpivot and pivot. The key is to transpose data so that you can use where [11] != [12].

    WITH CTE AS (
        SELECT * 
        FROM 
        (
            SELECT ID, colName, val
            FROM tblName
            UNPIVOT
            (
                val
                FOR colName IN ([p_x],[p_y],[p_z])
            ) unpiv
        ) src
        PIVOT
        (
            MAX(val)
            FOR ID IN ([11], [12])
        ) piv
    )
    SELECT colName
    --SELECT *
    FROM CTE WHERE [11] != [12]
    

    If there are only a few columns in the table, it's easy to simply put [p_x],[p_y],[p_z], but obviously it's not convenient to type 50 or more columns. Even though you may use this trick to drag and drop, or copy/paste, the column names from the table, it's still bulky. And for that, you may use the SELECT * EXCEPT strategy with dynamic sql.

    DECLARE @TSQL NVARCHAR(MAX), @colNames NVARCHAR(MAX)
    SELECT @colNames = COALESCE(@colNames + ',' ,'') + [name] 
    FROM syscolumns WHERE name  <> 'ID' and id = (SELECT id FROM sysobjects WHERE name = 'tablelName')
    
    SET @TSQL = '
        WITH CTE AS (
            SELECT * 
            FROM 
            (
                SELECT ID, colName, val
                FROM tablelName
                UNPIVOT
                (
                    val
                    FOR colName IN (' + @colNames + ')
                ) unpiv
            ) src
            PIVOT
            (
                MAX(val)
                FOR ID IN ([11], [12])
            ) piv
        )
        --SELECT colName
        SELECT *
        FROM CTE WHERE [11] != [12]
    '
    EXEC sp_executesql @TSQL
    

提交回复
热议问题