Login or Sign Up to become a member!
LessThanDot Site Logo

LessThanDot

Community Wiki

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.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

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

Navigation

Google Ads

Find Primary Keys and Columns Used in SQL Server

From Wiki

Jump to: navigation, search

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:

  1. select cons.TABLE_NAME
  2.     , cons.CONSTRAINT_NAME PK_NAME
  3.     , cols.COLUMN_NAME
  4. from INFORMATION_SCHEMA.TABLE_CONSTRAINTS cons
  5. left join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cols
  6. on cons.CONSTRAINT_NAME = cols.CONSTRAINT_NAME
  7. where cons.CONSTRAINT_TYPE = 'PRIMARY KEY'
  8. order by cons.TABLE_NAME
  9.     , cons.CONSTRAINT_NAME
  10.     , 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)

335 Rating: 2.5/5 (53 votes cast)