How to identify the referenced objects of an object in SQL Server

Here is a very small script that helps you to identify the referenced objects of an object in SQL Server.


Declare @ParentObject_name sysname = 'YOUR OBJECT'
;With cte as (
Select OBJECT_NAME(referencing_id) Parent_ObjectName,referenced_entity_name Referenced_ObjectName,
		ISNULL((Select type From sys.objects where name = SED.referenced_entity_name),'**')  ObjType
From sys.sql_expression_dependencies SED where referencing_id = object_id(@ParentObject_name)
union All
Select OBJECT_NAME(referencing_id),SED.referenced_entity_name,
		ISNULL((Select type From sys.objects where name = SED.referenced_entity_name),'**')  ObjType
From sys.sql_expression_dependencies SED 
Inner join cte c On SED.referencing_id = object_id(c.Referenced_ObjectName) 
Where OBJECT_NAME(referencing_id)  SED.referenced_entity_name and c.ObjType Is NOT NULL
)
Select * From cte  
Advertisements

Identify references of an object in SQL Server

Problem Statement:

Today, there was a requirement from one of my colleague “How to identify a function references in SQL Server?”.

Infact, He was looking for a script to identify the reference places(objects) where the function is being used in SQL Server. Please find the script below that we used to identify the references.

Script:

DECLARE @ObjectName NVARCHAR(100)
SET @ObjectName = N'split' --Give your function/proc name

--Table variable to hold the results from different databases
Declare @ResultTable Table(SourceSchema sysname, Sourceobject sysname, ReferencedDB sysname, ReferencedSchema sysname, ReferencedObject sysname)

Declare @MyQuery NVARCHAR(MAX) = N'
USE [?]
SELECT DISTINCT
	SourceSchema      = OBJECT_SCHEMA_NAME(sed.referencing_id)
	,SourceObject     = OBJECT_NAME(sed.referencing_id)
	,ReferencedDB     = ISNULL(sre.referenced_database_name, DB_NAME())
	,ReferencedSchema = ISNULL(sre.referenced_schema_name,
	OBJECT_SCHEMA_NAME(sed.referencing_id))
	,ReferencedObject = sre.referenced_entity_name
FROM sys.sql_expression_dependencies sed
CROSS APPLY sys.dm_sql_referenced_entities(OBJECT_SCHEMA_NAME(sed.referencing_id) + ''.'' +       	                           OBJECT_NAME(sed.referencing_id), ''OBJECT'') sre
WHERE sed.referenced_entity_name like ''%' + @ObjectName + '%'' AND sre.referenced_entity_name like ''%' + @ObjectName + '%''';

Insert into @ResultTable
EXEC sp_MSforeachdb  @MyQuery

Select * From @ResultTable

The above script uses sp_MSforeachdb to execute the query in all databases available in the SQL Server.

Please note that sp_MSforeachdb is an undocumented procedure, Microsoft may change the functionality or definition of this Stored Procedure at any time.

See Also:

You may be interested to know more on sp_MSforeachdb usage, please visit the below links

https://gallery.technet.microsoft.com/T-SQL-Script-Get-Table-Row-94e49d01
https://gallery.technet.microsoft.com/How-to-change-datacompressi-47dfce48