Sql server 2012 查找所有相关表

Sql server 2012 查找所有相关表,sql-server-2012,Sql Server 2012,我有一个大约有1000个表的数据库,我需要找到与特定表相关的所有表,比如customer表。我该如何进行 当您要求查找与特定表相关的所有表时,我假设您要求的是所有表都有一个外键引用到您的“customer”表。这是密切相关的。使用系统目录视图的以下查询应该可以做到这一点: select t.name as TableWithForeignKey, fk.constraint_column_id as FK_columns , c.name as ForeignKeyColumn fro

我有一个大约有1000个表的数据库,我需要找到与特定表相关的所有表,比如customer表。我该如何进行

当您要求查找与特定表相关的所有表时,我假设您要求的是所有表都有一个外键引用到您的“customer”表。这是密切相关的。使用系统目录视图的以下查询应该可以做到这一点:

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 

信息架构视图很有用:显然我的数据库不包含任何外键,所以我不得不使用“name%”之类的。当我尝试使用另一个数据库时,您的代码工作正常,因此感谢您的帮助:)