在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.
The sp_depends system stored procedure
SQL Server dynamic management functions including.
sys.dm_sql_referencing_entities
sys.dm_sql_referenced_entities
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 Server中查看对象依赖关系的更多相关文章
- SQL SERVER 2012 第五章 创建和修改数据表 の SQL SERVER中的对象名
[ServerName.[DataBaseName.[SchemeName.]]]ObjectName 服务器名,数据库名,模式名,对象名 其中模式是一个新出的坑爹的东西.
- SQL Server中授予用户查看对象定义的权限
SQL Server中授予用户查看对象定义的权限 在SQL Server中,有时候需要给一些登录名(用户)授予查看所有或部分对象(存储过程.函数.视图.表)的定义权限存.如果是部分存储过程.函数. ...
- 在SQL Server中实现关系模型
使用SQL Server的Transact-SQL(T-SQL)方言,此楼梯将为您提供如何使用SQL Server表中的数据的基本了解. DML是数据操作语言,是处理数据的语言的一个方面.它包括SEL ...
- 理解SQL Server中的权限体系(下)----安全对象和权限
原文:http://www.cnblogs.com/CareySon/archive/2012/04/12/SQL-Security-SecurableAndPermission.html 在开始阅读 ...
- 在SQL Server中实现关系模型的阶梯到级别3的t -SQL DML
在SQL Server中实现关系模型的阶梯到级别3的t -SQL DML 格雷戈里·拉森(Gregory Larsen),2017/08/02(第一次出版:2011 /11/09) 原文链接:http ...
- 到T-SQL DML 三级的阶梯:在SQL server中实现关系模型
作者: Gregory Larsen, 2017/08/02 (第一次出版: 2011/11/09) 翻译:谢雪妮,许雅莉,赖慧芳,刘琼滨 译文: 系列 该文章是阶梯系列的一部分:T-SQL DML的 ...
- net 架构师-数据库-sql server-001-SQL Server中的对象
1.1 数据库的构成 1.2 数据库对象概述 1.2.1 数据库对象 RDBMS 关系数据库管理系统 对象:数据库.索引.事务日志.CLR程序集.表 .报表.文件组.全文目录.图表.用户自定义数据类型 ...
- SQL Server中模式(schema)、数据库(database)、表(table)、用户(user)之间的关系
数据库的初学者往往会对关系型数据库模式(schema).数据库(database).表(table).用户(user)之间感到迷惘,总感觉他们的关系千丝万缕,但又不知道他们的联系和区别在哪里,对一些问 ...
- sql server中如何查看执行效率不高的语句
sql server中,如果想知道有哪些语句是执行效率不高的,应该如何查看呢?下面就将为您介绍sql server中如何查看执行效率不高的语句,供您参考. 在测量功能时,先以下命令清除sql se ...
随机推荐
- 九 DIP 依赖倒置原则
首先看定义: 1.高层模块不依赖于低层模块,两者都应该依赖于抽象层 2.抽象不能依赖于细节,细节必须依赖于抽象 首先,模块是个抽象的概念,可以大到一个系统中的子系统作为一个模块,也可以是某个子系统中的 ...
- Struts2+DAO层实现实例02——搭建DAO基本框架并与Struts2组合
实例内容 创建DAO(Data Access Oject)接口:BaseDAO 创建其实例化类:UserDAO 用于获取数据库struts中的userinfo表中的内容 创建User的Java Bea ...
- ESXI6.0 时间(时区)显示不一致
ESXI6.0 时间(时区)显示不一致 来源 http://blog.51cto.com/jdonghong/1957118 近日由于设置ESXI计划任务,无意间发现了esxi服务器客服端时间和系统显 ...
- 幸运数字(luckly)
幸运数字(luckly) 题目描述 A国共有 nn 座城市,这些城市由 TeX parse error: Misplaced & 条道路相连,使得任意两座城市可以互达,且路径唯一.每座城市都有 ...
- NFS排错案例
1.检验rpcinfo从客户端 # rpcinfo -p nfsserverip ,可以看到服务器端开的tcp/udp端口.默认都是打开的,客户端可以自己选择使用TCP/UDP program ver ...
- tips 前端 阻止 浏览器缓存静态资源
手机浏览器 uc上一直表现良好 qq浏览器还有微信上网址直接打开的(一样采用qq浏览器的内核) 大量缓存了静态资源 css js 图片 等这些当出现改动了刷新网页根本没有效果 电脑端浏览器没有问题 因 ...
- 笔记软件:三强篇EverNote、Mybase、Surfulater
通过上一篇<寻找最好的笔记软件:海选篇>的综合分析,作者发现有3种软件具有较明显的优势,可谓“笔记软件三强”.它们是:EverNote.Mybase 和 Surfulater.此三者相同之 ...
- Codevs 2080 特殊的质数肋骨
题目描述 Description 农民约翰的母牛总是产生最好的肋骨. 你能通过农民约翰和美国农业部标记在每根肋骨上的数字认出它们. 农民约翰确定他卖给买方的是真正的质数肋骨,是因为从右边开始切下肋 ...
- hdu6188&&百度之星初赛(B) T5
度度熊的交易计划 Problem Description 度度熊参与了喵哈哈村的商业大会,但是这次商业大会遇到了一个难题: 喵哈哈村以及周围的村庄可以看做是一共由n个片区,m条公路组成的地区. 由于生 ...
- EF4学习链接
原文发布时间为:2011-09-23 -- 来源于本人的百度文章 [由搬家工具导入] 1.Fluent API 的方式定义与数据库映射 2.利用特性实现与数据库的映射 3.EF的一些公约的介绍 4.E ...