List of all tables with a relationship to a given

2020-06-17 07:27发布

问题:

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

回答1:

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')


回答2:

-- To find all the foreign keys established to a table!
-- Columns: FKTABLE_NAME, FKCOLUMN_NAME
sp_fkeys @pktable_name='your table name here'


回答3:

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')