Tuesday, November 15, 2005

Find all Primary and Foreign Keys In A Database

To find all your foreign and primary keys in your database run the code below.
The ouput 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

USE Northwind

SELECT tc.TABLE_NAME AS PrimaryKeyTable,
tc.CONSTRAINT_NAME AS PrimaryKey,
COALESCE(rc1.CONSTRAINT_NAME,'N/A') AS ForeignKey ,
COALESCE(tc2.TABLE_NAME,'N/A') AS ForeignKeyTable
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1 ON tc.CONSTRAINT_NAME =rc1.UNIQUE_CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
WHERE TC.CONSTRAINT_TYPE ='PRIMARY KEY'
ORDER BY tc.TABLE_NAME,tc.CONSTRAINT_NAME,rc1.CONSTRAINT_NAME

1 comment:

  1. Anonymous10:50 AM

    SQL Server 2005 Setups Fails. I've followed all the instructions but keep getting this message:

    * If SQL Server Setup fails, Setup will roll back the installation but may not remove all .manifest files. The workaround is to rename the files and then rerun Setup. For more information, see How to: Work Around COM+ Check Failure in SQL Server Setup.

    I've used web search and have posted to newsgroups. I'm out of options and can't find the .manifest files that I'm supposed to rename. Can you help?

    csgallagher AT metromilwaukee.com

    ReplyDelete