How to find dependencies of stored procedures in SQL Server

Manually reviewing hundreds of stored procedures is time consuming. The sp_depends system stored procedure doesn’t always give proper / correct results when the object creation order is different or following deferred name resolution. The output below for the stored procedure SELECT_Account is missing the ENTRY and ACCOUNT tables.

sp_depends
sp_depends

SQL Server docs state that the procedure is in maintenance mode and may be removed in a future version of Microsoft SQL Server. Microsoft recommend using the sys.dm_sql_referencing_entities and sys.dm_sql_referenced_entities instead.

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

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

-- Objects on which the stored procedure @sp depends
SELECT 
    referenced_schema_name, 
    referenced_entity_name,
    referenced_minor_name,
    referenced_id,
    referenced_minor_id,
    referenced_class,
    referenced_class_desc
FROM 
    sys.dm_sql_referenced_entities(@sp, 'OBJECT')

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

Here is the correct output for the stored procedure SELECT_Account:

sys.sql_expression_dependencies
sys.sql_expression_dependencies

 

 

You May Also Like