Is there a quick query I can run that returns all columns of the same name between two tables?
I have many pairs of tables that I know are tied together, but I'm not sure which of the 50 or so columns they have in common.
Is there a quick query I can run that returns all columns of the same name between two tables?
I have many pairs of tables that I know are tied together, but I'm not sure which of the 50 or so columns they have in common.
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME in ('Table1', 'Table2')
group by COLUMN_NAME
having count(*) > 1
You can also do something like this to find all pairs without specifying names. This will match on views as well:
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
If you want to exclude the views, you can do this:
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
Here is how you can get the tables that have the same column name
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