2015-03-13 150 views
0

有兩個具有相同結構的表,如SQLFiddle,是否可以構建一個SQL語句來比較兩個表的列的值(其中id是唯一鍵),並在格式返回變更列的列表:比較和合並來自2個具有相同結構的表的數據

columnname, oldvalue, newvalue 

oldvalueTable1newvalue值在Table2值。

+0

提示:使用合適的軟件(MySQL,Oracle,DB2,...)和版本(例如, '的SQL服務器2014'。語法和功能的差異往往會影響答案。 – HABO 2015-03-13 13:51:00

回答

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 
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

+0

這是什麼?這不會產生所需的輸出,甚至不會使用提供的表模式。 – dario 2015-03-13 14:18:32

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) 
相關問題