Login or Sign Up to become a member!
LessThanDot Sit 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 friendfeed 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 all Primary and Foreign Keys In A Database

From Wiki

Jump to: navigation, search

To find all your foreign and primary keys in your database run the code below. The output will return the primary key, primary key table, foreign key, foreign key table. Primary keys that don't have foreign keys will have N/A in the foreign key output

  1. SELECT t.table_schema AS PrimarySchemaName ,
  2. t.TABLE_NAME AS PrimaryKeyTable,
  3. tc.CONSTRAINT_NAME AS PrimaryKey,
  4. COALESCE(tc2.constraint_schema,'N/A') AS ForeignSchemaName,
  5. COALESCE(rc1.CONSTRAINT_NAME,'N/A') AS ForeignKey ,
  6. COALESCE(tc2.TABLE_NAME,'N/A') AS ForeignKeyTable
  7. FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
  8. INNER JOIN INFORMATION_SCHEMA.TABLES t ON tc.TABLE_NAME = t.TABLE_NAME
  9. LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1 ON tc.CONSTRAINT_NAME =rc1.UNIQUE_CONSTRAINT_NAME
  10. LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
  11. WHERE TC.CONSTRAINT_TYPE ='PRIMARY KEY'
  12. ORDER BY tc.TABLE_NAME,tc.CONSTRAINT_NAME,rc1.CONSTRAINT_NAME


Here is another way, this one was emailed to us by one of our readers..thank you

  1. SELECT TC.CONSTRAINT_SCHEMA + '.'+ TC.TABLE_NAME AS PRIMARYKEYTABLE
  2. ,TC.CONSTRAINT_NAME AS PRIMARYKEY
  3. ,COALESCE(RC1.CONSTRAINT_NAME,'N/A') AS FOREIGNKEY
  4. ,CASE WHEN TC2.TABLE_NAME IS NULL THEN 'N/A'
  5.  ELSE TC.CONSTRAINT_SCHEMA + '.' + TC2.TABLE_NAME  END AS FOREIGNKEYTABLE
  6.  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
  7.  LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC1 ON TC.CONSTRAINT_NAME =RC1.UNIQUE_CONSTRAINT_NAME
  8.  LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC2 ON TC2.CONSTRAINT_NAME =RC1.CONSTRAINT_NAME
  9.  WHERE TC.CONSTRAINT_TYPE ='PRIMARY KEY'
  10.  ORDER BY TC.TABLE_NAME,TC.CONSTRAINT_NAME,RC1.CONSTRAINT_NAME


Contributed by: --SQLDenis 20:44, 29 May 2008 (GMT)

Part of SQL Server Programming Hacks

Section Usefull Admin stuff For The Developer

292 Rating: 2.5/5 (8 votes cast)