This code recursively looks at every Stored Procedure in your Stored Procedure and gives you the full list of all tables used.
declare @sp_name varchar(100)
declare @curSpName varchar(100)
declare @curObjName varchar(255)
declare @curXType varchar(1)
create table #tmpTables
(
proc_name varchar(255),
table_name varchar(255)
)
set @sp_name = 'STORED_PROCEDURE_NAME'
;WITH stored_procedures AS (
SELECT
o.name AS proc_name, oo.name AS table_name, oo.type AS xType,
ROW_NUMBER() OVER(partition by o.name,oo.name, oo.Type ORDER BY o.name,oo.name, oo.Type) 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'
--and oo.type = 'U' --Tables
and o.name = @sp_name)
SELECT proc_name, table_name, xType, 'N' Processed into ##tmpSP
FROM stored_procedures
WHERE row = 1
--ORDER BY proc_name,table_name
While (Select count(*) from ##tmpSP where Processed = 'N') 0
Begin
Select top 1 @curSpName = proc_name, @curObjName = table_name, @curXType = xType
from ##tmpSP
where Processed = 'N'
if @curXType = 'U'
Begin
insert into #tmpTables
values (@curSpName, @curObjName)
End
if @curXType = 'P'
Begin
;WITH stored_procedures AS (
SELECT
o.name AS proc_name, oo.name AS table_name, oo.type AS xType,
ROW_NUMBER() OVER(partition by o.name,oo.name, oo.Type ORDER BY o.name,oo.name, oo.Type) 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'
and oo.type = 'U' --Tables
and o.name = @curObjName)
insert into #tmpTables
SELECT @curSpName, table_name
FROM stored_procedures
WHERE row = 1
ORDER BY proc_name,table_name
;WITH stored_procedures AS (
SELECT
o.name AS proc_name, oo.name AS table_name, oo.type AS xType,
ROW_NUMBER() OVER(partition by o.name,oo.name, oo.Type ORDER BY o.name,oo.name, oo.Type) 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'
and oo.type = 'P' --SP's
and o.name = @curObjName)
insert into ##tmpSP
SELECT proc_name, table_name, xType, 'N'
FROM stored_procedures
WHERE row = 1
and proc_name not in
(
Select proc_name
from ##tmpSP
)
ORDER BY proc_name,table_name
End
if @curXType = 'v'
Begin
;WITH stored_procedures AS (
SELECT
o.name AS proc_name, oo.name AS table_name, oo.type AS xType,
ROW_NUMBER() OVER(partition by o.name,oo.name, oo.Type ORDER BY o.name,oo.name, oo.Type) 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 = 'v'
and oo.type = 'U' --Tables
and o.name = @curObjName)
insert into #tmpTables
SELECT proc_name, table_name
FROM stored_procedures
WHERE row = 1
ORDER BY proc_name,table_name
End
update ##tmpSP
set Processed = 'Y'
where table_name = @curObjName
End
Select distinct table_name
from #tmpTables
drop table #tmpTables
drop table ##tmpSP