Find Primary Keys and Columns Used in SQL Server
From Wiki
Every once in a while, even if for no reason other than his/her own sanity, a database developer or admin will need to see a list of all primary keys in a database, and the columns they contain. Luckily we have the INFORMATION_SCHEMA views available, that make finding this information a piece of cake. We can do this using two of the views, INFORMATION_SCHEMA.TABLE_CONSTRAINTS and INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE, as shown below:
- SELECT cons.TABLE_NAME
- , cons.CONSTRAINT_NAME PK_NAME
- , cols.COLUMN_NAME
- FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS cons
- LEFT join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cols
- ON cons.CONSTRAINT_NAME = cols.CONSTRAINT_NAME
- WHERE cons.CONSTRAINT_TYPE = 'PRIMARY KEY'
- ORDER BY cons.TABLE_NAME
- , cons.CONSTRAINT_NAME
- , cols.COLUMN_NAME
This returns a list of table names, along with their primary keys (null if there is no primary key). It also tells you the columns used in each.
Part of SQL Server Admin Hacks
Contributed by: --AlexCuse 18:35, 4 June 2008 (GMT)


