我是否可以运行快速查询,返回两个表之间所有相同名称的列?
我有许多表格,我知道它们绑在一起,但我不确定它们共有50个左右的列。
答案 0 :(得分:6)
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME in ('Table1', 'Table2')
group by COLUMN_NAME
having count(*) > 1
您也可以执行以下操作来查找所有对而不指定名称。这也将匹配视图:
select c1.COLUMN_NAME, c1.TABLE_NAME as Table1, c2.TABLE_NAME as Table2
from INFORMATION_SCHEMA.COLUMNS c1
inner join INFORMATION_SCHEMA.COLUMNS c2 on c1.COLUMN_NAME = c2.COLUMN_NAME and c1.TABLE_NAME <> c2.TABLE_NAME
order by 2, 1
如果要排除视图,可以执行以下操作:
select c1.COLUMN_NAME, c1.TABLE_NAME as Table1, c2.TABLE_NAME as Table2
from INFORMATION_SCHEMA.COLUMNS c1
inner join INFORMATION_SCHEMA.COLUMNS c2 on c1.COLUMN_NAME = c2.COLUMN_NAME and c1.TABLE_NAME <> c2.TABLE_NAME
inner join INFORMATION_SCHEMA.TABLES t1 on c1.TABLE_NAME = t1.TABLE_NAME and t1.TABLE_TYPE = 'BASE TABLE'
inner join INFORMATION_SCHEMA.TABLES t2 on c2.TABLE_NAME = t2.TABLE_NAME and t2.TABLE_TYPE = 'BASE TABLE'
order by 2, 1
答案 1 :(得分:2)
以下是如何获取具有相同列名的表
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN
(
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY COLUMN_NAME
HAVING COUNT (*) > 1
)
ORDER BY COLUMN_NAME, TABLE_NAME