-1

I've a database with huge number of tables. From these tables I want to list out all the column names that are appearing in more than one table along with the their table names.

I tried google search to find any suitable article that can explain how to achieve the results that I've described in the problem section.

No code snippets

No error messages.

Arulkumar
  • 12,966
  • 14
  • 47
  • 68
Manjunath
  • 1
  • 2
  • 2
    I'll surprised you found nothing if you searched. I suggest looking at `INFORMATION_SCHEMA.COLUMNS` or `sys.columns` and `sys.tables`. – Thom A May 27 '19 at 09:46

3 Answers3

1

This will return the column names and the table names:

select distinct 
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 TABLE_NAME, COLUMN_NAME
idstam
  • 2,848
  • 1
  • 21
  • 30
1

There are a lot of results and snippets that show how to get all column names in a database. It's a single query to sys.columns, eg :

select Name
from sys.columns

The same SQL queries that return multiple occurences in any table can be used here too, eg :

select Name,count(*)
from sys.columns
group by Name
having count(*)>1

Will return column names that occur more than once.

You can get the column and table names without joining by using COUNT() with OVER :

with t as (
    select name,
           object_name(object_id) as TableName,
           count(*) over (partition by name) cnt
    from sys.columns
)
select * 
from t
where cnt >1
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
0

The query below will return the column name along with the number of its occurences in the current database tables:

SELECT c.NAME AS 'ColumnName', COUNT(*) AS Occurences
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
GROUP BY c.NAME
HAVING COUNT(*) > 1

This query below will help to identify the specific column name is placed in which tables:

-- Find column name in all the tables
SELECT c.NAME AS 'ColumnName', t.NAME AS 'TableName'
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.NAME LIKE '%columnname%' -- to be searchable column name
ORDER BY TableName, ColumnName;
Arulkumar
  • 12,966
  • 14
  • 47
  • 68