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
But please note that the sysdepends will not give the table names if they are used in dynamic sql. What I suggest is to search reversely
ie: create a loop search the tables in the syscomments. The below stored procedure may help
CREATE PROCEDURE dbo.sp_getObjects
(
@ObjName VARCHAR(255)
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @Idkeyst INTEGER
DECLARE @Idkeyed INTEGER
DECLARE @tblName VARCHAR(255)
DECLARE @Objects VARCHAR(MAX)
IF NOT EXISTS(SELECT 1 FROM sys.objects where NAME = @ObjName AND type in ('P', 'FN','TR'))
BEGIN
PRINT 'NO Text Available for the Parameter'
RETURN(0)
END
CREATE TABLE #ProcStr
(
Idkey INT IDENTITY(1,1),
ScriptStr VARCHAR(MAX)
)
CREATE TABLE #Depends
(
Idkey INT IDENTITY(1,1),
Depends VARCHAR(255)
)
CREATE TABLE #Objects
(
Idkey INT IDENTITY(1,1),
ObjectName VARCHAR(255)
)
INSERT INTO #ProcStr
(ScriptStr)
EXEC sp_helptext @ObjName
DELETE #ProcStr WHERE LTRIM(ScriptStr) LIKE '--%'
DELETE #ProcStr WHERE LTRIM(REPLACE(ScriptStr,CHAR(9),'')) LIKE '--%'
SET @Idkeyst = 0
SET @Idkeyed = 0
WHILE 1=1
BEGIN
SELECT @Idkeyst = MIN(idKey) FROM #ProcStr WHERE ScriptStr like '%/*%' and Idkey > @Idkeyst
IF @Idkeyst IS NULL
BREAK
SELECT @Idkeyed = MIN(idKey) FROM #ProcStr WHERE ScriptStr like '%*/%' and Idkey >= @Idkeyst
DELETE #ProcStr WHERE Idkey >= @Idkeyst and Idkey <=@Idkeyed
END
DELETE #ProcStr WHERE ISNULL(LTRIM(REPLACE(ScriptStr,CHAR(9),'')),'')=''
INSERT INTO #Depends
(Depends)
SELECT DISTINCT t.name
FROM sys.sql_dependencies d
INNER JOIN sys.procedures p ON p.object_id = d.object_id
INNER JOIN sys.tables t ON t.object_id = d.referenced_major_id
where p.name = @ObjName
INSERT INTO #Objects
SELECT name from sys.objects o WHERE Type = 'U' AND NOT EXISTS
(SELECT 1 FROM #Depends WHERE Depends = o.name)
SET @Objects = ''
SELECT @Objects = CASE WHEN ISNULL(@Objects,'') = '' THEN '' ELSE @Objects+', ' END+ Depends
FROM #Depends
UPDATE #ProcStr
SET ScriptStr = LTRIM(RTRIM(ScriptStr))
UPDATE #ProcStr
SET ScriptStr = REPLACE(ScriptStr,CHAR(9),'')
UPDATE #ProcStr
SET ScriptStr = REPLACE(ScriptStr,CHAR(13),'')
UPDATE #ProcStr
SET ScriptStr = REPLACE(ScriptStr,CHAR(10),'')
SET @tblName = ''
SET @Idkeyst = 0
WHILE 1=1
BEGIN
SELECT @Idkeyst = MIN(idKey) FROM #Objects WHERE Idkey > @Idkeyst
IF @Idkeyst IS NULL
BREAK
SELECT @tblName = ObjectName FROM #Objects WHERE Idkey = @Idkeyst
IF Exists (SELECT 1 FROM #ProcStr WHERE (ScriptStr LIKE '% '+@tblName+' %'
OR ScriptStr LIKE '%.'+@tblName+' %' OR ScriptStr LIKE @tblName+' %' OR ScriptStr LIKE @tblName
--OR ScriptStr LIKE '%'+@tblName
OR ScriptStr LIKE '% '+@tblName+'''%' OR ScriptStr LIKE @tblName+'''%'))
BEGIN
SET @Objects = CASE WHEN ISNULL(@Objects,'')<>'' THEN @Objects+', '+@tblName ELSE @tblName END
END
END
IF ISNULL(@Objects,'') = ''
BEGIN
PRINT 'NO Tables are reffered in the stored procedures'
RETURN(0)
END
PRINT @Objects
SET NOCOUNT OFF
END