Sunday, December 18, 2011

Get list of referring table and column names

PROBLEM:
You want to get list of referring table and column names

SOLUTION:
To get list of referring table and column names

SELECT
       T.NAME AS TableWithForeignKey,
       FK.CONSTRAINT_COLUMN_ID AS FK_PartNo,
       C.NAME AS ForeignKeyColumn
FROM
       SYS.FOREIGN_KEY_COLUMNS AS FK
       INNER JOIN SYS.TABLES AS T ON FK.PARENT_OBJECT_ID = T.OBJECT_ID
       INNER JOIN SYS.COLUMNS AS C ON FK.PARENT_OBJECT_ID = C.OBJECT_ID
       AND FK.PARENT_COLUMN_ID = C.COLUMN_ID
WHERE
       FK.REFERENCED_OBJECT_ID = (
SELECT OBJECT_ID
FROM SYS.TABLES
WHERE NAME = 'MY_TABLE_NAME')
ORDER BY
       TableWithForeignKey,
       FK_PartNo

To get names of foreign key constraints

SELECT DISTINCT NAME
FROM SYS.OBJECTS
WHERE OBJECT_ID IN
(
SELECT FK.CONSTRAINT_OBJECT_ID FROM SYS.FOREIGN_KEY_COLUMNS AS FK
WHERE FK.REFERENCED_OBJECT_ID =
(SELECT OBJECT_ID FROM SYS.TABLES WHERE NAME = 'MY_TABLE_NAME')
)

If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!


No comments:

Post a Comment