Home > Database > Mysql Tutorial > How to Find Tables with Columns Matching a Specific Name in SQL?

How to Find Tables with Columns Matching a Specific Name in SQL?

Susan Sarandon
Release: 2025-01-20 00:41:09
Original
362 people have browsed it

How to Find Tables with Columns Matching a Specific Name in SQL?

Find the table containing the column with the specified name

Tables in a database contain columns with specific names. Useful to find all tables that contain a column with a specific name. This query allows you to identify these tables:

SQL query:

<code class="language-sql">SELECT      c.name  AS 'ColumnName'
            ,(SCHEMA_NAME(t.schema_id) + '.' + t.name) AS 'TableName'
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
WHERE       c.name LIKE '%MyName%'
ORDER BY    TableName
            ,ColumnName;</code>
Copy after login

Instructions:

This query joins the sys.columns and sys.tables tables to find the column name (c.name) and table name (TableName) that match the specified name ('MyName'). The SCHEMA_NAME function is used to include the schema name in the TableName result. Tables containing multiple matching columns can be easily identified by sorting by TableName and ColumnName.

Extended functions:

You can also include views in the search by replacing the sys.tables table with sys.objects:

<code class="language-sql">SELECT      COLUMN_NAME AS 'ColumnName'
            ,TABLE_NAME AS  'TableName'
FROM        INFORMATION_SCHEMA.COLUMNS
WHERE       COLUMN_NAME LIKE '%MyName%'
ORDER BY    TableName
            ,ColumnName;</code>
Copy after login

The above is the detailed content of How to Find Tables with Columns Matching a Specific Name in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template