How to find if Table/View is used in Stored Procedure in SQL Server

In this post, we are going to learn how to find out if the table is used in a Stored Procedure. we have multiple ways to do that.

This System Stored Procedure will return you list of table/views used by the Stored procedure/View. You can pass the view name or Stored Procedure as parameter,it will return you tables/views which are used in the object.

One disadvantage of using sp_depends is , it will not show you tables/views which are not in current database. If you have used objects from other databases, this information might be misleading.

--By using sp_depends, You can provide Stored Procedure Name or View name as parameter
EXEC sp_depends '[dbo].[GetCustomer]'



The 2nd method is to use the sys.sysdepends view with combination of sys.sysobjects to get the information. This also works the same way. It will not show you cross database objects ( Tables,Views) if have used in Stored Procedure or view definition.

--Get Information from sys.sysdepends 
SELECT DISTINCT OBJECT_NAME(SD.id) AS StoredProcedureNameName,
 OB.name AS TableOrViewName
 FROM sys.sysdepends SDINNER JOIN sys.sysobjects O 
ON SD.id=O.id
 INNER JOIN sys.sysobjects OB 
ON SD.depid=OB.id 
AND O.xtype='P'


3rd method is to use the sys.all_sql_modules system view. The definition column of this view has definition of Stored Procedure, Views, Functions etc.You can write query as given below to check if any of the Stored Procedure or object is using the table/view you are looking for.

--Use sys.all_sql_modules system view to get information if table is used
--in a Stored Procedure
 
SELECT OBJECT_NAME(OBJECT_ID),definition 
 FROM sys.all_sql_modules 
WHERE definition LIKE '%vw_Employee%'