Search code examples
sql-serverprimary-keysystem-views

Is there a view in SQL Server that lists just primary keys?


I'm working with SQL Server and trying to do a little "reflection," if you will. I've found the system view sys.identity_columns, which contains all of the identity columns for all of my tables.

However, I need to be able to select information about primary keys that aren't identity columns. Is there a view that contains data about all primary keys and only primary keys? If not, how else can I get this data?


Solution

  • This works for SQL Server 2005 and higher:

    select OBJECT_SCHEMA_NAME(i.object_id), OBJECT_NAME(i.object_id), i.name
    from sys.indexes i
    where i.is_primary_key = 1
    order by 1, 2, 3