There are lot of tables and sp in the db. I find the tables name which are used in the specific sp (stored procedure).
sp_depends %sp_name%
not give the
Looks like there is no complete answer for OP question. Most of the answers above don't have either schema name or include other objects (e.g. functions) used in stored procedures.
Full list of tables/views used in stored procedures with schema name and object id
SELECT DISTINCT
procObj.[object_id] AS [ProcObjectId],
procSchema.[name] AS [ProcSchema],
procObj.[Name] AS [ProcName],
tableObj.[object_id] AS [TableObjectId],
tableSchema.[name] AS [TableSchema],
tableObj.[Name] AS [TableName]
FROM sys.sql_dependencies AS dep
INNER JOIN sys.objects AS procObj
ON procObj.[object_id] = dep.[object_id]
INNER JOIN sys.schemas AS procSchema
ON procSchema.[schema_id] = procObj.[schema_id]
INNER JOIN sys.objects AS tableObj
ON tableObj.[object_id] = dep.[referenced_major_id]
INNER JOIN sys.schemas AS tableSchema
ON tableSchema.[schema_id] = tableObj.[schema_id]
WHERE procObj.[type] = 'P'
-- using this filter we can control dependent object types
-- e.g. tableObj.[type] IN ('U') - returns tables only
AND tableObj.[type] IN ('V', 'U')
Note that there is a filter on dependent object types which can be changed (depends on what you want in output results). Full list of type abbreviations is here.
;WITH stored_procedures AS (
SELECT
o.name AS proc_name, oo.name AS table_name,
ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
FROM sysdepends d
INNER JOIN sysobjects o ON o.id=d.id
INNER JOIN sysobjects oo ON oo.id=d.depid
WHERE o.xtype = 'P')
SELECT proc_name, table_name FROM stored_procedures
WHERE row = 1
ORDER BY proc_name,table_name
Here is the sql code for this
;WITH stored_procedures AS (
SELECT
o.name AS proc_name, oo.name AS table_name,
ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
FROM sysdepends d
INNER JOIN sysobjects o ON o.id=d.id
INNER JOIN sysobjects oo ON oo.id=d.depid
WHERE o.xtype = 'P')
SELECT proc_name, table_name FROM stored_procedures
WHERE row = 1
ORDER BY proc_name,table_name
.
There two ways to this
----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'
PS: sp_help
and sp_depends
does not always return accurate results.
Reference:
Try more elegant way (but, it's solution works only in MS SQL 2008 or higher) -
SELECT DISTINCT
[object_name] = SCHEMA_NAME(o.[schema_id]) + '.' + o.name
, o.type_desc
FROM sys.dm_sql_referenced_entities ('dbo.usp_test1', 'OBJECT') d
JOIN sys.objects o ON d.referenced_id = o.[object_id]
WHERE o.[type] IN ('U', 'V')