Last active
November 12, 2018 13:40
-
-
Save oskarnrk/4a3c790e7aa979ffcafb17a5539b1fb4 to your computer and use it in GitHub Desktop.
Get all tables and columns where a column is used as foreign key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Thanks to Dustin Ryan | |
-- https://sqldusty.com/2015/07/08/tsql-script-to-find-foreign-key-references-to-a-given-column/ | |
SELECT OBJECT_NAME(f.object_id) as ForeignKeyConstraintName, | |
OBJECT_NAME(f.parent_object_id) TableName, | |
COL_NAME(fk.parent_object_id,fk.parent_column_id) ColumnName, | |
OBJECT_NAME(fk.referenced_object_id) as ReferencedTableName, | |
COL_NAME(fk.referenced_object_id,fk.referenced_column_id) as ReferencedColumnName | |
FROM sys.foreign_keys AS f | |
INNER JOIN sys.foreign_key_columns AS fk | |
ON f.OBJECT_ID = fk.constraint_object_id | |
INNER JOIN sys.tables t | |
ON fk.referenced_object_id = t.object_id | |
WHERE OBJECT_NAME(fk.referenced_object_id) = 'your table name' | |
and COL_NAME(fk.referenced_object_id,fk.referenced_column_id) = 'your key column name' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment