Created
January 27, 2021 18:06
-
-
Save kking124/4e0e3936defbb9c6b67785aed80d6461 to your computer and use it in GitHub Desktop.
list database foreign keys
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
-- source: https://stackoverflow.com/questions/925738/how-to-find-foreign-key-dependencies-in-sql-server | |
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 | |
ORDER BY PK_Table, PK_Column |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment