在SQL Server中查看对象依赖关系

本文涉及的产品
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
云数据库 RDS SQL Server,基础系列 2核4GB
简介: 原文 在SQL Server中查看对象依赖关系 Viewing object dependencies in SQL Server   Deleting or changing objects may affect other database objects like views or ...

原文 在SQL Server中查看对象依赖关系

Viewing object dependencies in SQL Server

 

Deleting or changing objects may affect other database objects like views or procedures that depends on them and in certain instances, can “break” the depending object. An example can be that if a View queries a table and the name of that table changes. The View will no longer function.

 

In SQL Server there are several ways to find object dependencies.

  1. The sp_depends system stored procedure

  2. SQL Server dynamic management functions including.

    • sys.dm_sql_referencing_entities

    • sys.dm_sql_referenced_entities

  3. The View Dependencies feature in SQL Server Management Studio (SSMS).

sp_depends

sp_depends is a system stored procedure that displays information about all object types (e.g. procedures, tables, etc) that depend on the object specified in the input parameter as well as all objects that the specified object depends on.

The sp_depends procedure accepts one parameter, the name of a database object. E.g. EXECUTEsp_depends ‘ObjectName’

Below are examples, which will be used in this article:

 

 

-- New database
CREATE DATABASE TestDB;
GO

USE TestDB GO CREATE TABLE UserAddress ( AddresID INT PRIMARY KEY IDENTITY(1, 1) ,FirstName VARCHAR(100) ,Lastname VARCHAR(150) ,Address VARCHAR(250) ) GO 

 

 

-- New procedure
CREATE PROCEDURE sp_GetUserAddress
AS
BEGIN
	SELECT FirstName ,Lastname ,Address FROM UserAddress END GO CREATE TABLE Address ( ID INT NOT NULL IDENTITY(1, 1) ,City VARCHAR(120) ,PostalCode INT ,UserAddressID INT FOREIGN KEY REFERENCES UserAddress(AddresID) ) GO 

 

-- New View
CREATE VIEW v_Address
AS
SELECT ID
	,City ,PostalCode ,UserAddressID FROM dbo.Address GO CREATE PROCEDURE sp_GetUserCity AS BEGIN SELECT UserAddress.FirstName ,UserAddress.Lastname ,Address.City FROM UserAddress INNER JOIN Address ON UserAddress.AddresID = Address.UserAddressID END GO 

 

 

 

-- New Trigger
CREATE TRIGGER trgAfterInsert ON [dbo].[UserAddress]
FOR INSERT AS PRINT 'Data entered successfully' GO 

 

Let’s run these scripts above to create the test objects then execute the following SQL.

 

 

EXECUTE sp_depends 'UserAddress'

 

The following result will be:

  name type
1 dbo.sp_GetUserAddress stored procedure
2 dbo.sp_GetUserCity stored procedure

 

  • name – name of dependent object

  • type – type of dependent object (e.g. table)

If a stored procedure is specified as an argument value in sp_depends, then a name of the table and the column names on which the procedure depends will be shown.

Let’s see how this looks with sp_GetUserAddress

 

 

EXECUTE sp_depends 'sp_GetUserAddress'

 

The following result will be:

  name type updated selected column
1 dbo.UserAddress user table no yes FirstName
2 dbo.UserAddress user table no yes LastName
3 dbo.UserAddress user table no yes Addresss

 

  • name – name of dependent object

  • type – type of dependet object (e.g. table)

  • updated – whether the object is updated or not

  • selected – object is used in the SELECT statement

  • column – column on which the dependency exists

sp_depends does not display triggers.

To illustrate this execute the following code in the query window:

 

 

CREATE TRIGGER trgAfterInsert ON [dbo].[UserAddress]
FOR INSERT AS PRINT 'Data entered successfully' GO 

Now execute the sp_depends over the UserAddress table, the trgAfterInsert will not appear in the Results table:

  name type
1 dbo.sp_GetUserAddress stored procedure
2 dbo.sp_GetUserCity stored procedure

 

sp_dependes in some case does not report dependencies correctly. Let’s look at the situation when an object (e.g. UserAddress) on which other object depends (e.g. sp_GetUserAddress) is deleted and recreated. When sp_dependes is executed using EXECUTE sp_depends ‘sp_GetUserAddress’ or EXECUTE sp_depends ‘UserAddress’ the following message will appear:

“Object does not reference any object, and no objects reference it.”

Sadly, sp_dependes is on the path to deprecation and will be removed from future versions of the SQL Server. But you can use sys.dm_sql_referencing_entities and sys.dm_sql_referenced_entities instead.

sys.dm_sql_referencing_entities

 

This function returns all objects from the current database which depend on the object that is specified as an argument.

Type the following in the query window:

 

 

SELECT referencing_schema_name
	,referencing_entity_name
FROM sys.dm_sql_referencing_entities('dbo.UserAddress', 'Object') 

The result will be:

  referencing_schema_name referencing_entity_name
1 dbo sp_GetUserAddress
2 dbo sp_GetUserCity

 

referencing_schema_name – schema of the referencing entity

referencing_entity_name – name of the referencing object

More information about result sets can be found on this link.

sys.dm_sql_referenced_entities

 

This system function returns all objects from the current database on which specified object depends on.

Enter the following code in the query window:

 

 

SELECT referenced_entity_name
	,referenced_minor_name
FROM sys.dm_sql_referenced_entities('dbo.sp_GetUserAddress', 'Object') 

The following result will be shown:

  referenced_entity_name referenced_minor_name
1 UserAddress NULL
2 UserAddress FirstName
3 UserAddress Lastname
4 UserAddress Address

 

referenced_entity_name – Name of the referenced object

referenced_minor_name – Name of the column of the referenced entity

For detailed information about result sets, please visit page on this link.

Referencing vs referenced

 

The objects that are appears inside the SQL expression are called the referenced entity and the objects which contain expressions are called referencing entity:

When using these two function the schema name (e.g. dbo) must be specified as part of the object name:

 

 

SELECT referencing_schema_name
	,referencing_entity_name
FROM sys.dm_sql_referencing_entities('dbo.UserAddress', 'Object') 

 

Otherwise no results will be displayed. Run the query without shema nema (dbo):

 

 

SELECT referencing_schema_name
	,referencing_entity_name
FROM sys.dm_sql_referencing_entities('UserAddress', 'Object') 

 

The result will be empty set:

  referencing_schema_name referencing_entity_name
     

 

An empty result set will be shown under these situations:

  • When is an invalid parameter passed (e.g. ‘dbo.UserAddress’,’NN’ insteaddbo.UserAddress’,’Object’)

  • When a system object is specified as argument (e.g. sys.all_columns)

  • When the specified object does not reference any objects

  • The specified object does not exist in the current database

The message 2020

 

Typically the message 2020 occurs when a referencing object e.g. procedure, calls a referenced object e.g. table or a column from the table that does not exist. For example, if in the Address table change name of the column City to name Town and execute the SELECT * FROM sys.dm_sql_referenced_entities (‘[dbo].[v_Address]’,’Object’) query, the message 2020 will appear.

Execute the following code:

 

 

EXEC sys.sp_rename 'dbo.Address.City'
	,'Town'
	,'COLUMN' SELECT * FROM sys.dm_sql_referenced_entities('dbo.v_Address', 'OBJECT') 

 

The following message will appear:


Msg 207, Level 16, State 1, Procedure v_Address, Line 6
Invalid column name ‘City’.
Msg 2020, Level 16, State 1, Line 3
The dependencies reported for entity “dbo.v_Address” might not include references to all columns. This is either because the entity references an object that does not exist or because of an error in one or more statements in the entity. Before rerunning the query, ensure that there are no errors in the entity and that all objects referenced by the entity exist.

Troubleshooting

In order to prevent dropping or modifying objects, which depends on another object, the v_Address view should be altered and added the WITH SCHEMABINDING option:

 

 

ALTER VIEW v_Address
	WITH SCHEMABINDING
AS
SELECT ID
	,City ,PostalCode ,UserAddressID FROM dbo.Address 

 

Now, when changing the name of the column in the Address table, the following message will appear, which proactively provides information that the object, the table “City” in this example, is a part of another object.

Code:

 

 

EXEC sys.sp_rename 'dbo.Address.City'
	,'Town'
	,'COLUMN' 

 

Message:

Msg 15336, Level 16, State 1, Procedure sp_rename, Line 501
Object ‘dbo.Address.City’ cannot be renamed because the object participates in enforced dependencies.

Schema-bound vs Non-schema-bound

There are two types of dependencies: Schema-bound and Non-schema-bound dependencies.

A Schema-bound dependency (SCHEMABINDING) prevents referenced objects from being altered or dropped as long as the referencing object exists

A Non-schema-bound dependency: does not prevent the referenced object from being altered or dropped.

For sys.dm_sql_referenced_entities and sys.dm_sql_referencing_entities dependency information will not be displayed for temporary tables, temporary stored procedures or system objects.

Below is an example of a temporary procedure:

 

 

CREATE PROCEDURE #sp_tempData
AS
BEGIN
	SELECT AddresID
		,FirstName ,Lastname ,Address FROM UserAddress END 

 

Now, when executing sys.dm_sql_referencing_entities for the table UserAddress the information about the #sp_tempData procedure that depends on the UserAddress will not be shown in the list.

Code:

 

 

SELECT referencing_schema_name
	,referencing_entity_name
FROM sys.dm_sql_referencing_entities('dbo.UserAddress', 'Object') 

 

Result:

  referencing_schema_name referencing_entity_name
1 dbo sp_GetUserAddress
2 dbo sp_GetUserCity

 

Viewing Dependencies

Another way to view dependencies between objects is by using the View Dependencies option from SSMS. From the Object Explorer pane, right click on the object and from the context menu, select the View Dependencies option:

This will open the Object Dependencies window. By default, the Object that depend on radio button is selected. This radio button will list in the Dependencies section all objects that depends on the selected object (e.g. Address):

If selected the Object on which radio button, will display in the Dependencies section all objects on which selected object (e.g. Address) depends:

The Selected object section consists of three fields:

  • Name – name of the selected object from the Dependencies list

  • Type – type of the selected object (e.g.table)

  • Dependency type – dependency between two objects (Schema-bound, Non-schema-bound).

Under the Type field the Unresolved Entity type for the object can be appear. This happens when the objects refer to an object that don’t exist in the database. This is equivalent to the Msg 2020 message that appears when using sys.dm_sql_referencing_entities or sys.dm_sql_referenced_entities functions:

3rd party dependency viewer

 

ApexSQL Search is a free add-in, which integrates into SSMS and Visual Studio for SQL object and data text search, extended property management, safe object rename, and relationship visualization.

The add-in can be downloaded from this link.

To see object dependencies, right-click on an object (e.g. stored procedure) from the Object Explorer, and choose the View dependencies option from the ApexSQL Search drop-down menu:

Or select object in the Object Explorer, from the ApexSQL main menu, choose ApexSQL Search menu and from the list select the View dependencies option:

After clicking the Dependency viewer window will appear with the Dependencies pane, which shows all objects that depends on the selected object (e.g. UserAddress), by default this pane appears in lower right side of the Dependency viewer window:

Dependency viewer provides graphical view of all dependencies between objects in the middle of the Dependency viewer window:

Visual dependencies

The Dependency viewer offers various options for filtering, appearance and manipulating objects.

In the Object filter pane, the object types (e.g. view) that will be displayed in the dependency graph can be specified:

In the Object browser pane, specific objects can be selected that will be shown or omitted from the dependency graph:

The Dependencies pane, the complete dependency chain for the selected object in the dependency graph (e.g. Address) can be shown. Children indicate the object that depend on the selected object (aka referencing) and Parents shows the objects from which selected object depends on (aka referenced):

The Layout option under the Display ribbon offers different options for visual organization and display:

For example, the Hierarchical option will organize objects based on the “generation” e.g. parents, children, decendents, so the parent (aka Referencing) will be at the top (UserAddress) and object descendants (aka Referenced) will be under them (sp_GetUserCity). Object of the same generation will be in the same horizontal level:

Using this option, it can easily be determined how many objects depend on a specific object and a determination can be made as to whether it is safe to delete it without breaking relationships

The labels that appears in the dependency graph above (e.g. Select, Trigger, etc.) describe the type of relationship e.g. Select, DRI

For example, there is “Select” label on the relationship between the UserAddress table and sp_GetUserAddress procedure. This is because sp_GetUserAddress contains a SELECT statement referencing the UserAddress table.

On the relationship between two other tables we see the “DRI” label. Declarative Referential Integrity (DRI) exists between SQL tables only and indicate, in this case, that in the object (FOREIGN KEY – UserAddressID) exists in the Address table that references to the object from the UserAddress table (PRIMARY KEY – AddressID):

The Type option allows choosing which type of relationship will be included in the dependency graph e.g. Children only:

For example, the Parents and descendants option will show all dependencies for the selected object (UserAddress). This option will show the complete dependency chain, including parents, children, and descendants:

More information about the Layout and Type options can be found on this link.

See also:

相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情: https://www.aliyun.com/product/rds/sqlserver
目录
相关文章
|
8天前
|
关系型数据库 MySQL 网络安全
5-10Can't connect to MySQL server on 'sh-cynosl-grp-fcs50xoa.sql.tencentcdb.com' (110)")
5-10Can't connect to MySQL server on 'sh-cynosl-grp-fcs50xoa.sql.tencentcdb.com' (110)")
|
2月前
|
SQL 关系型数据库 MySQL
INSERT INTO t_a.tableName SELECT * FROM t_b.tableName 如何通过定义一个list对象,包含多个tableName,循环执行前面的sql,用MySQL的语法写
【8月更文挑战第7天】INSERT INTO t_a.tableName SELECT * FROM t_b.tableName 如何通过定义一个list对象,包含多个tableName,循环执行前面的sql,用MySQL的语法写
29 5
|
3月前
|
SQL 存储 监控
SQL Server的并行实施如何优化?
【7月更文挑战第23天】SQL Server的并行实施如何优化?
68 13
|
3月前
|
SQL
解锁 SQL Server 2022的时间序列数据功能
【7月更文挑战第14天】要解锁SQL Server 2022的时间序列数据功能,可使用`generate_series`函数生成整数序列,例如:`SELECT value FROM generate_series(1, 10)。此外,`date_bucket`函数能按指定间隔(如周)对日期时间值分组,这些工具结合窗口函数和其他时间日期函数,能高效处理和分析时间序列数据。更多信息请参考官方文档和技术资料。
|
3月前
|
SQL 存储 网络安全
关系数据库SQLserver 安装 SQL Server
【7月更文挑战第26天】
48 6
|
2月前
|
SQL 安全 Java
驱动程序无法通过使用安全套接字层(SSL)加密与 SQL Server 建立安全连接。错误:“The server selected protocol version TLS10 is not accepted by client
驱动程序无法通过使用安全套接字层(SSL)加密与 SQL Server 建立安全连接。错误:“The server selected protocol version TLS10 is not accepted by client
232 0
|
3月前
|
存储 SQL C++
对比 SQL Server中的VARCHAR(max) 与VARCHAR(n) 数据类型
【7月更文挑战7天】SQL Server 中的 VARCHAR(max) vs VARCHAR(n): - VARCHAR(n) 存储最多 n 个字符(1-8000),适合短文本。 - VARCHAR(max) 可存储约 21 亿个字符,适合大量文本。 - VARCHAR(n) 在处理小数据时性能更好,空间固定。 - VARCHAR(max) 对于大文本更合适,但可能影响性能。 - 选择取决于数据长度预期和业务需求。
151 1
|
3月前
|
SQL Oracle 关系型数据库
MySQL、SQL Server和Oracle数据库安装部署教程
数据库的安装部署教程因不同的数据库管理系统(DBMS)而异,以下将以MySQL、SQL Server和Oracle为例,分别概述其安装部署的基本步骤。请注意,由于软件版本和操作系统的不同,具体步骤可能会有所变化。
170 3
|
3月前
|
SQL 存储 安全
数据库数据恢复—SQL Server数据库出现逻辑错误的数据恢复案例
SQL Server数据库数据恢复环境: 某品牌服务器存储中有两组raid5磁盘阵列。操作系统层面跑着SQL Server数据库,SQL Server数据库存放在D盘分区中。 SQL Server数据库故障: 存放SQL Server数据库的D盘分区容量不足,管理员在E盘中生成了一个.ndf的文件并且将数据库路径指向E盘继续使用。数据库继续运行一段时间后出现故障并报错,连接失效,SqlServer数据库无法附加查询。管理员多次尝试恢复数据库数据但是没有成功。
下一篇
无影云桌面