Technical Article

Search all objects in all DBs for code fragments

,

This procedure allows you to search through all objects in all databases on your server for words/phrases in your object code.  Very handy for cases in which, for example, a column name on a table has been changed and you need to search your entire server for any sprocs/views/etc. that might reference it.

Syntax: [EXEC] sp_FindCodeStr [@SearchStr=]'', [@PrintOnly=]{0, 1}

Notice that no cursors or temp tables are used in this sproc.  Dynamic T-SQL execution appends all the needed statements onto the @sql variable, building the batch in a set-oriented manner, and then the final batch is executed via sp_executesql.  As a result, this sproc performs surprisingly well.

USE MASTER
GO

CREATE PROCEDURE sp_FindCodeStr
@SearchStr varchar(1000),
@PrintOnly bit = 0

AS

SET NOCOUNT ON

DECLARE @sql nvarchar(4000)

SELECT @sql = ISNULL(@sql + char(13) + 'UNION ALL' + char(13), '') +
'SELECT DISTINCT ''' + name + ''' as db, o.name
FROM ' + name + '.dbo.sysobjects o
JOIN ' + name + '.dbo.syscomments c
ON o.id = c.id
WHERE text like ''%' + @SearchStr+ '%''
/* Elminate system objects & VSS objects */AND name not like ''sys%''
AND name not like ''dt/_%'' ESCAPE ''/''
AND name not like ''fn/_%'' ESCAPE ''/'''

FROM sysdatabases
WHERE name NOT IN('master', 'model', 'tempdb', 'msdb')

IF @PrintOnly = 1 PRINT @sql

ELSE EXEC sp_executesql @sql

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating