Loading ...

How to find all the foreign key constraints in a database

Who is online?  0 guests and 0 members
home  »  forums   »  asp.net topics   »  data access   » How to find all the foreign key constraints in a database

How to find all the foreign key constraints in a database

Posts under the topic: How to find all the foreign key constraints in a database

Posted: 5/11/2010

Lurker 170  points  Lurker
  • Joined on: 10/17/2009
  • Posts: 34

Hi experts,

I have a requirement for my db where I need to find all the foreign key constraints in my db. How can I do so ?

 


tags sql

Posted: 5/11/2010

Contributor 2255  points  Contributor
  • Joined on: 11/30/2008
  • Posts: 11
  Answered

shawn said:

Hi experts,

I have a requirement for my db where I need to find all the foreign key constraints in my db. How can I do so ?

 

Hi Shawn,

use this query to find all foreign key in database. simply run the following query:

SELECT 
    FK_Table  = FK.TABLE_NAME, 
    FK_Column = CU.COLUMN_NAME, 
    PK_Table  = PK.TABLE_NAME, 
    PK_Column = PT.COLUMN_NAME, 
    Constraint_Name = C.CONSTRAINT_NAME 
FROM 
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C 
    INNER JOIN 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK 
        ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME 
    INNER JOIN 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK 
        ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME 
    INNER JOIN 
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU 
        ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME 
    INNER JOIN 
    ( 
        SELECT 
            i1.TABLE_NAME, i2.COLUMN_NAME 
        FROM 
            INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 
            INNER JOIN 
            INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 
            ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME 
            WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' 
    ) PT 
    ON PT.TABLE_NAME = PK.TABLE_NAME 
-- optional: 
ORDER BY 
    1,2,3,4



Posted: 5/11/2010

Guru 16518  points  Guru
  • Joined on: 4/19/2009
  • Posts: 483
  Answered

SELECT  FK.name AS ForeignKey,
OBJECT_NAME(FK.parent_object_id) AS TableName,
COL_NAME(FKC.parent_object_id, FKC.parent_column_id) AS ColumnName,
OBJECT_NAME(FK.referenced_object_id) AS ReferenceTableName,
COL_NAME(FKC.referenced_object_id, FKC.referenced_column_id) AS ReferenceColumnName
FROM [sys].[foreign_keys] AS FK
INNER JOIN [sys].[foreign_key_columns] AS FKC
ON FK.OBJECT_ID = FKC.constraint_object_id

OR

 

SELECT  ITC.constraint_name,
ITC.table_name,
IKCU.column_name,
ICCU.table_name AS foreign_table_name,
ICCU.column_name AS foreign_column_name
FROM [information_schema].[table_constraints] AS ITC
JOIN [information_schema].[key_column_usage] AS IKCU ON ITC.constraint_name = IKCU.constraint_name
JOIN [information_schema].[constraint_column_usage] AS ICCU ON ICCU.constraint_name = ITC.constraint_name
WHERE constraint_type = 'FOREIGN KEY'


tags SQL
Page 1 of 1 (3 items)