bl1234
bl1234

Reputation: 163

SQL to list all tables that does not have a particular column in their index

I want to list all the tables which does not contain a particular column in their index but the column exist in the table schema.

I referenced List of all index & index columns in SQL Server DB but the query is listing all the tables with all the index.

For example, if the table schema contains a column 'Date' and the index does not contain the column 'Date' then i want to list this table in my result.

Upvotes: 1

Views: 921

Answers (1)

Bruce Dunwiddie
Bruce Dunwiddie

Reputation: 2908

DECLARE @search_column SYSNAME;

SET @search_column = 'Date';

SELECT s.name AS [Schema], t.name AS [Table]
FROM
    sys.schemas s
        INNER JOIN sys.tables t ON
            t.[schema_id] = s.[schema_id]
        INNER JOIN sys.columns c ON
            c.[object_id] = t.[object_id]
WHERE
    c.name = @search_column AND
    NOT EXISTS
    (
        SELECT *
        FROM
            sys.indexes i
                INNER JOIN sys.index_columns ic ON
                    ic.[object_id] = i.[object_id] AND
                    ic.index_id = i.index_id
        WHERE
            i.[object_id] = t.[object_id] AND
            ic.column_id = c.column_id
    )
ORDER BY
    s.name,
    t.name;

Upvotes: 1

Related Questions