Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
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)



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.