查找 SQL Server 中表的相关性

在本文中,我们将通过管理工作室和查询向您展示如何在 SQL Server 中查找表的相关性。在修改或删除表时,了解表的相关性非常有用。

这是论坛上最常被问到的问题之一。为了演示这一点,我们使用了 Adventure Works 数据库中存在的人力资源.Employee 表。

查找 SQL Server 中表的相关性

有两种方法可以查找表的相关性

使用 SSMS 查找表的相关性

您可以使用 SQL Server Management Studio 来查看表的相关性。为此,请转到对象资源管理器 -> 展开 Adventure Works 数据库文件夹 -> 并找到您想查找相关性的表。

右键单击表名,然后从上下文菜单中选择“查看相关性”选项。

Find the Dependencies of a Table in SQL Server 2

选择“查看相关性”选项后,将打开以下窗口。此窗口有两个选项:

依赖于 Employee 的对象:此 SQL Server 选项将显示所有依赖于 Employee 表的表、函数和视图。

Object Dependencies window 3

Employee 依赖的对象:此选项显示 Employee 表所依赖的所有表。

Find the Dependencies of a Table 4

以下是 Employee 表的相关性列表。

Find the Dependencies of a Table 5

使用查询查找 SQL Server 中表的相关性

您也可以使用查询来查找表的相关性。

SQL Server 中查找表相关性的方法 1

在此示例中,我们使用了 SP_DEPENDS 存储过程。它会返回指定对象的所有相关性,包括表、视图、存储过程、约束等。

USE [AdventureWorks2014]
GO
EXEC sp_depends @objname = N'HumanResources.Employee' ;
EXEC sp_depends 6

这是查找表相关性的另一种方法。

USE [AdventureWorks2014]
GO
SELECT referencing_id, 
       referencing_schema_name, 
       referencing_entity_name 
FROM sys.dm_sql_referencing_entities('HumanResources.Employee', 'OBJECT');
Find the Dependencies of a Table 7

查找表相关性的方法 3

USE [AdventureWorks2014]
GO

SELECT ROUTINE_SCHEMA,
       ROUTINE_NAME, 
       ROUTINE_TYPE,
       ROUTINE_DEFINITION 
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_DEFINITION LIKE '%Employee%'
Select * from INFORMATION_SCHEMA.ROUTINES  8

查找表相关性的方法 4

USE [AdventureWorks2014]
GO

SELECT *
	FROM sys.sql_expression_dependencies A, sys.objects B
	WHERE referenced_id = OBJECT_ID(N'HumanResources.Employee') AND 
		A.referencing_id = B.object_id  
GO
Find the Dependencies of a Table 9

我认为选择所需的列比使用 SELECT * 更好。

USE [AdventureWorks2014]
GO

SELECT referenced_schema_name, 
       referenced_entity_name, 
       name, 
       type_desc, 
       create_date 
FROM sys.sql_expression_dependencies A, sys.objects B
WHERE referenced_id = OBJECT_ID(N'HumanResources.Employee') AND 
	A.referencing_id = B.object_id  
GO
Find the Dependencies of a Table 10