如何使用SQL找出存储过程的依赖关系

bq9c1y66  于 2022-09-18  发布在  Java
关注(0)|答案(4)|浏览(164)

我想要一个脚本,将显示数据库中存储过程的依赖性。实际上,当我们手动执行视图依赖时,这将花费大量时间,我有500多个存储过程。所以,我想知道这些存储过程是否在数据库中使用,这样我就可以删除无用的存储过程。

sp_depends没有显示所有结果,因为我需要依赖于此存储过程‘usp_Constant_Get_Pvt’的所有对象及其依赖的对象。

EXEC sp_depends @objname = N'usp_Constant_Get_Pvt'
iklwldmw

iklwldmw1#

我在类似的情况下使用此脚本(不要忘记使用模式名称):

--
DECLARE
    @sp nvarchar(100)
SET @sp = N'dbo.usp_Constant_Get_Pvt'

-- Objects that depends on [@sp]
SELECT 
    referencing_schema_name, 
    referencing_entity_name
FROM sys.dm_sql_referencing_entities(@sp, 'OBJECT')

-- Objects on which [@sp] depends
SELECT 
    referenced_schema_name, 
    referenced_entity_name
FROM sys.dm_sql_referenced_entities(@sp, 'OBJECT')

SELECT
    referenced_schema_name, 
    referenced_entity_name
FROM sys.sql_expression_dependencies
WHERE referencing_id = OBJECT_ID(@sp)
iqih9akk

iqih9akk2#

尝试使用以下查询

SELECT 
    referencing_schema_name, 
    referencing_entity_name,
    referencing_id, 
    referencing_class_desc, 
    is_caller_dependent
FROM sys.dm_sql_referencing_entities ('YourObject', 'OBJECT');

有关更多详细信息,请参阅This link

xlpyo6sf

xlpyo6sf3#

下面的代码将使用表达式依赖关系来找出存储过程上的依赖关系。表达式依赖项的优势在于,它们还可以找到跨数据库依赖项。但是,如果有动态SQL,我们必须在sql_modules中进行搜索。

Reference URL

引用存储过程的对象

SELECT OBJECT_SCHEMA_NAME ( referencing_id ) AS referencing_schema_name,  
    OBJECT_NAME(referencing_id) AS referencing_entity_name,   
    o.type_desc AS referencing_desciption,   
    COALESCE(COL_NAME(referencing_id, referencing_minor_id), '(n/a)') AS referencing_minor_id,   
    referencing_class_desc, referenced_class_desc,  
    referenced_server_name, referenced_database_name, referenced_schema_name,  
    referenced_entity_name,   
    COALESCE(COL_NAME(referenced_id, referenced_minor_id), '(n/a)') AS referenced_column_name,  
    is_caller_dependent, is_ambiguous  
FROM sys.sql_expression_dependencies AS sed  
INNER JOIN sys.objects AS o ON sed.referencing_id = o.object_id  
WHERE referenced_id = OBJECT_ID(N'SchemaName.StoredProcedureName');  
GO

存储过程中引用的对象

SELECT OBJECT_NAME(referencing_id) AS referencing_entity_name,   
    o.type_desc AS referencing_desciption,   
    COALESCE(COL_NAME(referencing_id, referencing_minor_id), '(n/a)') AS referencing_minor_id,   
    referencing_class_desc,  
    referenced_server_name, referenced_database_name, referenced_schema_name,  
    referenced_entity_name,   
    COALESCE(COL_NAME(referenced_id, referenced_minor_id), '(n/a)') AS referenced_column_name,  
    is_caller_dependent, is_ambiguous  
FROM sys.sql_expression_dependencies AS sed  
INNER JOIN sys.objects AS o ON sed.referencing_id = o.object_id  
WHERE referencing_id = OBJECT_ID(N'SchemaName.StoredProcedureName');  
GO
plicqrtu

plicqrtu4#

尝试以下SQL Server脚本:

SELECT referencing_schema_name, referencing_entity_name, referencing_id, referencing_class,  referencing_class_desc, is_caller_dependent
FROM sys.dm_sql_referencing_entities(N'usp_Constant_Get_Pvt' , 'OBJECT')

相关问题