views:

22

answers:

2

I have many table in my database it contain many key relation. i need to list out the table and its corresponding key name and the relationship table.

+1  A: 

Try

SELECT t.table_schema AS PrimarySchemaName ,
t.TABLE_NAME AS PrimaryKeyTable,
tc.CONSTRAINT_NAME AS PrimaryKey,
COALESCE(tc2.constraint_schema,'N/A') AS ForeignSchemaName,
COALESCE(rc1.CONSTRAINT_NAME,'N/A') AS ForeignKey ,
COALESCE(tc2.TABLE_NAME,'N/A') AS ForeignKeyTable
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN INFORMATION_SCHEMA.TABLES t ON tc.TABLE_NAME = t.TABLE_NAME
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

From here: http://wiki.lessthandot.com/index.php/Find_all_Primary_and_Foreign_Keys_In_A_Database

SQLMenace
this will not find all FKs, it seems to only find FKs that are on a PK. If you have a table with a unique constraint/index on a column and FK that to another table, that relation will be missing.
KM
+1  A: 

Another way

EXEC sp_help 'your_table_name'
Madhivanan
But how to get all FKS of my database???
Ayyappan.Anbalagan
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTSwhere constraint_type='FOREIGN KEY'
Madhivanan