简体   繁体   中英

How to find identical columns in multiple tables in SQL

Is there a simpler way to find matching column names in multiple tables?

The only way I know how to do this currently is to check each table individually but some tables have a bunch of columns and I know my human eye can miss things.

For SQL Server:

SELECT      c.name, string_agg(t.name, ', ')
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
group by c.name

Use information_schema.columns . For instance, to get all column names in multiple tables:

select column_name, string_agg( concat(table_schema, '.', table_name), ',')
from information_schema.columns
group by column_name
having count(*) > 1;

The information_schema views are actually standard and available in many databases, including SQL Server.

In Oracle

Use DBA_TAB COLUMNS or ALL_TAB_COLUMNS table it contains names of columns with table name and other details

Vladimir's answer is right and specific to SQL Server.

Another good answer is to use INFORMATION_SCHEMA views to retrieve what you're looking for. INFORMATION_SCHEMA is a standard follow by some DBMS to provides a common view for common objects.

https://en.wikipedia.org/wiki/Information_schema

https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/system-information-schema-views-transact-sql?view=sql-server-ver15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM