Determine a table's primary key using TSQL

rein picture rein · Oct 6, 2009 · Viewed 58.3k times · Source

I'd like to determine the primary key of a table using TSQL (stored procedure or system table is fine). Is there such a mechanism in SQL Server (2005 or 2008)?

Answer

Stuart Ainsworth picture Stuart Ainsworth · Oct 6, 2009

This should get you started:

SELECT 
    *
FROM 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
    JOIN 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu 
        ON tc.CONSTRAINT_NAME = ccu.Constraint_name
WHERE 
    tc.TABLE_NAME = 'TableName' AND 
    tc.CONSTRAINT_TYPE = 'Primary Key'