Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / debugging

MS SQL Server - SQL Object Dependency Check

4.00/5 (1 vote)
4 Dec 2011CPOL 13.8K  
Check if dependency of a table are objects referenced by a stored proc. A system table with CTE can help to identify dependency quickly.

Use the following SP:


SQL
CREATE PROC [dbo].GetDependentObjectList @ObjectName AS sysname 
AS

WITH ObjectDepends(entity_name,referenced_database_name,referenced_schema, 
                   referenced_entity, referenced_id,level)
AS(    
SELECT entity_name = CASE referencing_class                              
                       WHEN 1 THEN OBJECT_NAME(referencing_id)
                       WHEN 12 THEN (SELECT t.name 
                                     FROM sys.triggers AS t                                            
                                     WHERE t.object_id = sed.referencing_id)                              
                       WHEN 13 THEN (SELECT st.name 
                                     FROM sys.server_triggers AS st                                           
                                     WHERE st.object_id = sed.referencing_id) COLLATE database_default 
                     END,
       referenced_database_name,
       referenced_schema_name,
       referenced_entity_name,
       referenced_id,
       0 AS level     
 FROM SYS.SQL_Expression_Dependencies AS sed     
WHERE OBJECT_NAME(referencing_id) = @ObjectName 

UNION ALL    

SELECT entity_name = CASE sed.referencing_class                              
                       WHEN 1 THEN OBJECT_NAME(sed.referencing_id)                              
                       WHEN 12 THEN (SELECT t.name FROM sys.triggers AS t                                            
                                     WHERE t.object_id = sed.referencing_id)                              
                       WHEN 13 THEN (SELECT st.name 
                                     FROM sys.server_triggers AS st
                                     WHERE st.object_id = sed.referencing_id) COLLATE database_default 
                     END,
        sed.referenced_database_name,
        sed.referenced_schema_name,
        sed.referenced_entity_name,
        sed.referenced_id,level + 1
 FROM ObjectDepends AS o    
 JOIN SYS.SQL_Expression_Dependencies AS sed 
      ON sed.referencing_id = o.referenced_id) 

SELECT entity_name AS referencing_entity, referenced_database_name,
       referenced_schema,referenced_entity, level  
  FROM ObjectDepends 
 ORDER BY level;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)