我有兩個具有相同列名稱的表,並且每個主鍵的大部分值都相同。對於某些主鍵,某些值是不同的。我想要捕獲其值與另一個表不同的列名稱列表。比較兩個表中的所有列並獲取更改的列名稱
例如,可以說我有兩個表A_old a_new進行和
A_old
a_new進行
我要像下面
我需要一個更好的方法輸出做到這一點。我不需要完整的查詢..我需要的是一個更好的方法。誰能幫我。
我有兩個具有相同列名稱的表,並且每個主鍵的大部分值都相同。對於某些主鍵,某些值是不同的。我想要捕獲其值與另一個表不同的列名稱列表。比較兩個表中的所有列並獲取更改的列名稱
例如,可以說我有兩個表A_old a_new進行和
A_old
a_new進行
我要像下面
我需要一個更好的方法輸出做到這一點。我不需要完整的查詢..我需要的是一個更好的方法。誰能幫我。
我想下面的查詢會給出所需的行。
SELECT
AO.col1
,List_of_changes =
CASE
WHEN AO.col2 = AN.col2 AND AO.col3 = AN.col3 AND AO.col4 = AN.col4 THEN 'NO CHANGES'
WHEN AO.col2 <> AN.col2 AND AO.col3 <> AN.col3 AND AO.col4 <> AN.col4 THEN 'col2, col3, col4'
WHEN AO.col2 = AN.col2 AND AO.col3 = AN.col3 AND AO.col4 <> AN.col4 THEN 'col4'
WHEN AO.col2 = AN.col2 AND AO.col3 <> AN.col3 AND AO.col4 <> AN.col4 THEN 'col3, col4'
WHEN AO.col2 = AN.col2 AND AO.col3 <> AN.col3 AND AO.col4 = AN.col4 THEN 'col3'
WHEN AO.col2 <> AN.col2 AND AO.col3 = AN.col3 AND AO.col4 = AN.col4 THEN 'col2'
WHEN AO.col2 <> AN.col2 AND AO.col3 <> AN.col3 AND AO.col4 = AN.col4 THEN 'col2,col3'
WHEN AO.col2 <> AN.col2 AND AO.col3 = AN.col3 AND AO.col4 <> AN.col4 THEN 'col2,col4'
--and so on
END
FROM
A_old AO
INNER JOIN A_new AN ON
AN.col1 = AO.col1
在這裏,我認爲*可以用CASE語句替換,以查看匹配行中的哪些列匹配並生成所需的值。
讓我試試這種方法,如果它的工作,我會將它標記爲答案。謝謝..! –
如果我有20多列,該怎麼辦?有沒有其他方法?不能我們更新list_of_changes使用concat函數爲每個情況時語句..? –
我可以理解20 +列會創建太多的case語句來處理。我還沒有研究過替代方法。我會盡量抽出時間研究一下。 –
SELECT col1, col2, col3, col4
FROM
(
SELECT *
FROM a_old
UNION ALL
SELECT *
FROM a_new
) t
GROUP BY col1, col2, col3, col4
HAVING COUNT(*) = 1
ORDER BY col1;
甚至可以使用動態sql查詢。
查詢
DECLARE @sql AS varchar(max);
SELECT @sql = 'select t1.col1, ' + STUFF((SELECT
'+ case when t1.' + column_name + ' = t2.' + column_name + ' then ''''
else ''' + column_name + ''' end '
FROM information_schema.columns
WHERE table_name = 'A_new'
AND column_name <> 'col1'
ORDER BY column_name
FOR xml PATH (''))
, 1, 2, '') + ' as list_of_changes from A_old t1 join A_new t2 on t1.col1 = t2.col1';
SELECT @sql = 'select t.col1, case when len(t.list_of_changes) = 0 then ''No changes''
else t.list_of_changes end as list_of_changes
from(' + @sql + ')t;';
EXEC (@sql);
除了'mysql'和'sql',有點混在那裏。還應該添加哪些其他標籤。就像PHP,JAVA一樣,因爲我相信你所付出的迴應是一個頁面的動態響應 –
你使用的是什麼工具集? MySQL的? SQL Server?兩者同時? MySQL中有一個表,而另一個表是SQL Server? –
這兩個表僅在SQL Server中。我正在刪除mysql標籤.. –