比较和合并具有相同结构的2个表中的数据

时间:2015-03-13 13:09:53

标签: sql-server tsql sql-server-2014

有两个具有相同结构的表,如SQLFiddle,是否可以构建一个SQL语句来比较两个表的列的值(其中id是唯一键),并返回一个列表格式的更改列:

columnname, oldvalue, newvalue

其中oldvalueTable1中的值,而newvalue中的值是Table2中的值。

3 个答案:

答案 0 :(得分:0)

您可以这样做:

SELECT T1.Id
      ,'Name' AS ColumnName
      ,CAST(T1.name AS VARCHAR(MAX)) AS OldValue
      ,CAST(T2.name AS VARCHAR(MAX)) AS NewValue
FROM Table1 AS T1
FULL OUTER JOIN Table2 AS T2
  ON T1.id = T2.id
UNION
SELECT T1.Id
      ,'Amount'
      ,CAST(T1.amount AS VARCHAR(MAX))
      ,CAST(T2.amount AS VARCHAR(MAX))
FROM Table1 AS T1
FULL OUTER JOIN Table2 AS T2
  ON T1.id = T2.id

答案 1 :(得分:0)

您需要使用MERGE语句,请注意它只能从SQL 2008开始使用

这是一个例子

MERGE Production.ProductInventory AS target
USING (SELECT ProductID, SUM(OrderQty) FROM Sales.SalesOrderDetail AS sod
    JOIN Sales.SalesOrderHeader AS soh
    ON sod.SalesOrderID = soh.SalesOrderID
    AND soh.OrderDate = @OrderDate
    GROUP BY ProductID) AS source (ProductID, OrderQty)
ON (target.ProductID = source.ProductID)
WHEN MATCHED AND target.Quantity - source.OrderQty <= 0
    THEN DELETE
WHEN MATCHED 
    THEN UPDATE SET target.Quantity = target.Quantity - source.OrderQty, 
                    target.ModifiedDate = GETDATE()
OUTPUT $action, Inserted.ProductID, Inserted.Quantity, Inserted.ModifiedDate, Deleted.ProductID,
    Deleted.Quantity, Deleted.ModifiedDate;
GO

您可以在SQL merge

了解有关合并的更多信息

答案 2 :(得分:0)

如果您只想要有差异的行:

SELECT COALESCE(T1.Id, T2.Id) Id
      ,'Name' AS ColumnName
      ,CAST(T1.name AS VARCHAR(MAX)) AS OldValue
      ,CAST(T2.name AS VARCHAR(MAX)) AS NewValue
FROM Table1 AS T1
FULL OUTER JOIN Table2 AS T2
  ON T1.id = T2.id 
WHERE COALESCE(T1.name,'**') != COALESCE(T2.name ,'**')
UNION ALL
SELECT COALESCE(T1.Id, T2.Id) Id
      ,'Amount' AS ColumnName
      ,CAST(T1.Amount AS VARCHAR(MAX)) AS OldValue
      ,CAST(T2.Amount AS VARCHAR(MAX)) AS NewValue
FROM Table1 AS T1
FULL OUTER JOIN Table2 AS T2
  ON T1.id = T2.id 
WHERE COALESCE(T1.Amount,0) != COALESCE(T2.Amount,0)