How to search all objects in all databases with specific word phrase in SQL Server

When migrating SQL databases to new server, one of the challenge is to identify all the hard-coded references to old servers or services. Here is a small piece of code that I wrote to search all databases to identify all objects with references to specific keywords or phases.

DECLARE @listReferenceObjects TABLE
  (
      [DBName] varchar(300),
      [Object_Name] varchar(300),
      [Type_Desc] varchar(500)
  )
DECLARE @KeyWord varchar(300), @Stmt varchar(max)
SET @KeyWord='SOMETHING YOU WANT TO SEARCH'

SET @Stmt=REPLACE('
         SELECT DISTINCT ''?'' DBName, o.name AS Object_Name, o.Type_Desc
         FROM ?.sys.sql_modules m 
         INNER JOIN ?.sys.objects o 
         ON m.object_id=o.object_id
         WHERE m.definition Like ''%KEYWORD%''
     ',
     'KEYWORD',
     @KeyWord)

INSERT INTO @listReferenceObjects
EXEC sp_msforeachdb @Stmt

SELECT * FROM @listReferenceObjects

Leave a Reply