Sql-Server

計算數據庫中所有表中常見列名的數量

  • May 8, 2020

有沒有辦法在數據庫中比較每個表,列出每個表之間的公共列數?如果可能的話,我更喜歡使用 join 而不是 subquery 和information_schema.columnsover sys.columns

例如,如果我有 4 個表,我希望輸出如下:

list1        list2        commonColumns  
-----       --------     --------------------
table1     table2         1
table1     table3         2
table1     table4         0
table2     table1         1
table2     table3         5
table2     table4         2
table3     table1         3 
table3     table2         0
table3     table4         1
table4     table1         2
table4     table2         3
table4     table3         0

您可能需要模式名稱和表名稱,這是一種從正確的目錄視圖獲取資訊的方法,而不是INFORMATION_SCHEMA更多關於為什麼在這裡)。

;WITH c AS 
(
 SELECT 
   t = QUOTENAME(OBJECT_SCHEMA_NAME([object_id])) 
     + '.' + QUOTENAME(OBJECT_NAME([object_id])), 
   name
 FROM sys.columns
 WHERE OBJECTPROPERTY([object_id], 'IsMsShipped') = 0
)
SELECT 
  list1 = c1.t, 
  list2 = c2.t, 
  commonColumns = COUNT(CASE WHEN c1.name = c2.name THEN 1 END)
FROM c AS c1
INNER JOIN c AS c2
ON c1.t < c2.t
GROUP BY c1.t, c2.t
ORDER BY c1.t, c2.t;

SQLFiddle 展示

引用自:https://dba.stackexchange.com/questions/44909