Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Script to find Foreign keys to a specific table?

Is there a query that will get me foreign keys directed at a specific table column? For example, say I had these three tables:

__________
|Table A |
----------
|Id      |
----------

___________
|Table B  |
-----------
|Id       |
|TableAId | (Foreign Key to TableA.Id)
-----------

___________
|Table C  |
-----------
|Id       |
|TableAId | (Foreign Key to TableA.Id)
-----------

I need a query along the lines of "Select * Foreign Keys directed at TableA.Id" that returned "Table C: TableAId", "Table B: TableAId". I'm browsing through some of the INFORMATION_SCHEMA system views, and it seems like I can easily see what foreign keys belong to Table A, or Table B individually, but I can't find where it says "Table C has a foreign key to Table A" specifically. I can figure out the specifics of the query, I just can't find the views I'm looking for (or I'm glossing over them). Any help would be appreciated.

like image 947
Ocelot20 Avatar asked Oct 21 '11 17:10

Ocelot20


People also ask

How do you find all tables that have foreign keys that reference particular table column?

To see foreign key relationships of a table: SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA. KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = 'db_name' AND REFERENCED_TABLE_NAME = 'table_name';


1 Answers

Courtesy of Pinal Dave:

SELECT 
    f.name AS ForeignKey,
    OBJECT_NAME(f.parent_object_id) AS TableName,
    COL_NAME(fc.parent_object_id,
    fc.parent_column_id) AS ColumnName,
    OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
    COL_NAME(fc.referenced_object_id,
    fc.referenced_column_id) AS ReferenceColumnName
FROM 
    sys.foreign_keys AS f
    INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
like image 127
Michael Fredrickson Avatar answered Nov 06 '22 00:11

Michael Fredrickson