List of all tables with a relationship to a given

2020-06-17 07:57发布

In SQL Server is there a command to return a list of all tables with a relationship to a given table or view?

EDIT: SQL SERVER 2008

3条回答
萌系小妹纸
2楼-- · 2020-06-17 08:05

For SQL Server 2005 and up, use something like:

SELECT
    name, OBJECT_NAME(parent_object_id) 'Table'
FROM 
    sys.foreign_keys
WHERE 
    referenced_object_id = OBJECT_ID('Your-referenced-table-name-here')
查看更多
萌系小妹纸
3楼-- · 2020-06-17 08:14
-- To find all the foreign keys established to a table!
-- Columns: FKTABLE_NAME, FKCOLUMN_NAME
sp_fkeys @pktable_name='your table name here'
查看更多
啃猪蹄的小仙女
4楼-- · 2020-06-17 08:21

Say your table name is TableX. If you want to know all foreign key relationships (columns of TableX referenced in other tables and columns of other tables referenced in TableX) you could do this:

select name 'ForeignKeyName', 
    OBJECT_NAME(referenced_object_id) 'RefrencedTable',
    OBJECT_NAME(parent_object_id) 'ParentTable'
from sys.foreign_keys
where referenced_object_id = OBJECT_ID('TableX') or 
    parent_object_id = OBJECT_ID('TableX')
查看更多
登录 后发表回答