Example:: Searching Stored Procedures Across SQL Server Databases
Example:: Searching Stored Procedures Across SQL Server Databases
Heres a little utility SP I wrote which searches all stored procedures in all databases in your SQL
Server Instance for an input string.
In SQL Server Management Studio 2008 there is an option to do filtered searches but it only look
inside the selected database. Now honestly I am not sure you should be in a position where you
would want to search stored procedures across Databases, but if you do find the need, hope this
is useful!
Example:
If you compile this utility into DB1, then simply say :
EXEC DB1..sp_SearchInSPs 'mySearchString'
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
Sajjan Sarkar with help of SungUngKim
-- Create date: April 26, 2011
-- Description: stored procedure to search all SPs for a given string in ALL
databases.
-- =============================================
-- Sample to run
--EXEC DB1..sp_SearchInSPs 'BillingOvertimeCalcFactor'
create PROCEDURE [dbo].[sp_SearchInSP]
(
-- Add the parameters for the stored procedure here
@SearchString VARCHAR(100) = ''
)
AS
BEGIN
--Declare
DECLARE @SString NVARCHAR(50)
DECLARE @getdbname SYSNAME
DECLARE @sqlstm NVARCHAR(1000)
CREATE TABLE #tmp
(
DBName VARCHAR(100) ,
SPName VARCHAR(100)
)
DECLARE dbname CURSOR
FOR
--get all the names of the Databases in order by name
SELECT '[' + name + ']'
FROM
master.dbo.sysdatabases
ORDER BY name
OPEN dbname
--Get the first Name
FETCH NEXT FROM dbname INTO @getdbname
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @getdbname
--set the search string
SET @SString = @SearchString
--append the search pattern
SET @SString = '%' + @SString + '%'
SET @sqlstm = 'SELECT DISTINCT ''' + @getdbname + ''',
s.name
FROM
' + @getdbname + '.dbo.syscomments c
INNER JOIN '+ @getdbname +'.dbo.sysobjects s
ON
c.id = s.id
WHERE
s.type IN ( ''p'', ''tr'' )
AND c.text LIKE ''%' + @SString + '%''
ORDER BY [Name]'
BEGIN
INSERT
VALUES
RETURN
INTO @tbl
( items )
( CAST(@list AS VARCHAR)
)
-- items - varchar(4000)
END
SET @textpos = 1
SET @leftover = ''
WHILE @textpos <= DATALENGTH(@list) / 2
BEGIN
SET @chunklen = 4000 - DATALENGTH(@leftover) / 2
SET @tmpstr = LTRIM(@leftover + SUBSTRING(@list, @textpos,
@chunklen))
SET @textpos = @textpos + @chunklen
SET @pos = CHARINDEX(@Delim, @tmpstr)
WHILE @pos > 0
BEGIN
SET @str = SUBSTRING(@tmpstr, 1, @pos - 1)
IF LTRIM(RTRIM(@str)) <> ''
INSERT @tbl
( items )
VALUES ( @str )
SET @tmpstr = LTRIM(SUBSTRING(@tmpstr, @pos + 1,
LEN(@tmpstr)))
SET @pos = CHARINDEX(@Delim, @tmpstr)
END
SET @leftover = @tmpstr
END
IF LTRIM(RTRIM(@leftover)) <> ''
INSERT @tbl
( items )
VALUES ( @leftover )
RETURN
END