2012-12-27 37 views
3

我有一个大约有1000个表的数据库,我需要找到与特定表相关的所有表,比如说客户表。我如何继续?查找所有相关的表

+0

信息架构视图是有帮助的:http://msdn.microsoft.com/en-us/library/ms186778.aspx – rene

回答

10

当您要求查找与特定表相关的所有表时,我假设您要求所有具有对“客户”表的外键引用的表。这与previous Stack Overflow question密切相关。使用该系统目录视图下面的查询应该做的伎俩:

select t.name as TableWithForeignKey, fk.constraint_column_id as FK_columns , 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 = 'customers') 
    order by TableWithForeignKey, ForeignKeyColumn 

MSDN sys.foreign_key_columns

+0

显然我的数据库没有包含任何外键,所以我不得不使用'name%'。你的代码工作,当我尝试与另一个数据库,所以感谢您的帮助:) – Swiftly