Created
August 7, 2014 10:01
-
-
Save nabil-hassan/c91b2758b7e55a7e2350 to your computer and use it in GitHub Desktop.
SQL Server: Find all foreign key columns that reference primary key column
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
-- Find all fk columns that reference the specified PK column | |
DECLARE @BASE_TABLE_NAME VARCHAR(255) = 'RD_CLAIM_CLOSURE_REASON' | |
DECLARE @BASE_COLUMN_NAME VARCHAR(255) = 'ID' | |
SELECT r.TABLE_NAME fk_table_name, | |
r.COLUMN_NAME fk_column_name | |
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE U | |
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FK | |
ON U.CONSTRAINT_CATALOG = FK.UNIQUE_CONSTRAINT_CATALOG | |
AND U.CONSTRAINT_SCHEMA = FK.UNIQUE_CONSTRAINT_SCHEMA | |
AND U.CONSTRAINT_NAME = FK.UNIQUE_CONSTRAINT_NAME | |
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE R | |
ON R.CONSTRAINT_CATALOG = FK.CONSTRAINT_CATALOG | |
AND R.CONSTRAINT_SCHEMA = FK.CONSTRAINT_SCHEMA | |
AND R.CONSTRAINT_NAME = FK.CONSTRAINT_NAME | |
WHERE U.COLUMN_NAME = @BASE_COLUMN_NAME | |
AND U.TABLE_NAME = @BASE_TABLE_NAME |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment