A blog about SQL Server, SSIS, C# and whatever else I happen to be dealing with in my professional life.

Find ramblings

Wednesday, April 13, 2011

Find tables without primary key

Normally, I would expect this query to return zero rows as a table without a primary key is fairly useless from my point of view. However, we have a few databases with warts like that and I had to get a list of those tables back to the people that design said tables as they didn't know... I digress.

Query to find tables without primary key constraint

In theory, this query should work against any database that implements that ANSI standard set of INFORMATION_SCHEMA tables. In practice, I can only say this works for SQL Server 2005 through SQL Denali, Engine of the Devil, CTP1.
SELECT DISTINCT
    T.TABLE_CATALOG
,   T.TABLE_SCHEMA
,   T.TABLE_NAME
FROM
    INFORMATION_SCHEMA.TABLES T
    LEFT OUTER JOIN
        INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
        ON TC.TABLE_NAME = T.TABLE_NAME
            AND TC.TABLE_SCHEMA = T.TABLE_SCHEMA
            AND TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
WHERE
    TC.TABLE_NAME IS NULL
    AND T.TABLE_TYPE = 'BASE TABLE'

No comments: