我有81个表,我想找到匹配的列并输出如下列表:
"columnName" found in 3 tables:
table1
table2
table3
"columnName2" found in 4 tables:
table1
table3
table4
table5
答案 0 :(得分:0)
表INFORMATION_SCHEMA.COLUMNS
是一个系统表,其中包含所有表的所有列。您可以从中选择它来查看它。
对于你的问题,你应该试试这个:
select I.Column_name,
table_name,
table_count
from INFORMATION_SCHEMA.COLUMNS I
inner join
(
Select Column_name,
count(*) as table_count
from INFORMATION_SCHEMA.COLUMNS
group by Column_name) as T on T.Column_name = I.Column_name
您将拥有一个表,其中包含每个column_name,表和table_count
列中的计数。
我不知道如何输出列表。你应该把它放在Excel上,如果你想格式化我猜...
告诉我你是否有问题!
答案 1 :(得分:0)
查询下方应该会给你想要的结果。如果您遇到任何问题,请告诉我。如果要特定于单个数据库,可以修改脚本
此查询为您提供列名称 - 已删除的表名称 - 表格数量
SELECT t.CNAME AS ColumnName, STUFF(
(SELECT ',' + S.TNAME
FROM
(
SELECT C.NAME AS CNAME , T.NAME AS TNAME
FROM SYS.OBJECTS AS T
JOIN SYS.COLUMNS AS C
ON T.OBJECT_ID=C.OBJECT_ID
WHERE T.TYPE_DESC='USER_TABLE'
)s
WHERE s.CNAME = t.CNAME
FOR XML PATH('')),1,1,'') AS TablesUsed,
COUNT(t.TNAME)
FROM
(
SELECT C.NAME AS CNAME , T.NAME AS TNAME
FROM SYS.OBJECTS AS T
JOIN SYS.COLUMNS AS C
ON T.OBJECT_ID=C.OBJECT_ID
WHERE T.TYPE_DESC='USER_TABLE'
)t
GROUP BY t.CNAME
HAVING COUNT(t.TNAME) > 1
ORDER BY COUNT(t.TNAME) DESC