我想找到所有依赖于给定表的db对象,包括通过外键引用给定表的其他表。我尝试使用“sp_depends”,它给了我sprocs,视图和触发器,但没有告诉我其他表有哪些外键到给定的表。有什么帮助吗?
答案 0 :(得分:9)
select OBJECT_NAME(parent_object_id), OBJECT_NAME(referenced_object_id)
from sys.foreign_keys
where referenced_object_id = object_id('SchemaName.TableName')
答案 1 :(得分:2)
关键因素是sys.foreign_keys视图。我在mssqltips.com的文章中找到了一个可能有用的查询... Identify all of your foreign keys in a SQL Server database
答案 2 :(得分:1)
在SSMS中:右键单击表格,然后点击"View Dependencies"
答案 3 :(得分:1)
也试试这个:
USE AUX; <- use your database name
GO
SELECT f.name AS ForeignKey,
SCHEMA_NAME(f.SCHEMA_ID) SchemaName,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName,
SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName,
OBJECT_NAME(f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id
GO
在最后一次开始之前,您可以添加where OBJECT_NAME(f.parent_object_id) = 'your_table_name'
以仅查看该表的依赖关系。
它会打印TableName | Column name (FK) | Reference TableName | Reference Column Name