简体   繁体   中英

Searching in SQL Management Studio 2005

Is there a way to search for text within stored procedures? For example I want to find out if a particular table is being referenced by any stored procedure.

SELECT
   OBJECT_SCHEMA_NAME(object_id) + '.' + OBJECT_NAME(object_id)
FROM
   sys.sql_modules
WHERE
   definition like '%whatever%'

syscomments is legacy and splits the definition into nvarchar 4000 chunks thus risking not finding what you want. The same applies to INFORMATION_SCHEMA.ROUTINES

Red Gate has a free tool called Sql Search that I rather like. It keeps an index so that after its first search, it is very fast (and even the first one is pretty good...). It can search for text in procs as well as table and view definitions, etc. There are some filtering features to make it a little easier to use. And the search results are displayed in a very useful manner, with the full text of the object and the search text highlighted.

Use:

SELECT OBJECT_NAME(m.object_id), m.*
  FROM SYS.SQL_MODULES m
 WHERE m.definition like N'%text_youre_looking_for%'

SYSCOMMENTS and INFORMATION_SCHEMA.routines have NVARCHAR(4000) columns. So if "text_youre_looking_for" is used at position 3998, it won't be found. SYSCOMMENTS does have multiple lines, but INFORMATION_SCHEMA.routines truncates.

My co-worker graciously provided me with this one recently. It does some similar searching as others have noted, but with a little more added in.

DECLARE
 @chvStringToFind varchar(256), /* String to find */
 @chrObjectType char(2),--=null, /* Only look for objects of this type */
 @intNbCharToExtract int
 --=50 /* Number of characters to extract before and after the string to find */
 --exec DBA_FindStringInDB @chvStringToFind='sp_helpdia', @chrObjectType=null, @intNbCharToExtract=50
 SET @chvStringToFind = 'EnterSearchTextHere'  -- Change this to search
 SET @chrObjectType = NULL
 SET @intNbCharToExtract = 50

 SELECT t.Name, t.TypeDescription, t.CreationDate, t.ModificationDate,
 '...' + SUBSTRING
 (
 t.ObjectDefinition,
 CHARINDEX(@chvStringToFind, t.ObjectDefinition) - @intNbCharToExtract,
 LEN(@chvStringToFind) + (@intNbCharToExtract*2)
 ) + '...' AS Extract
 FROM
 (
 SELECT o.name AS Name, 
 o.type_desc AS TypeDescription, 
 o.create_date AS CreationDate, o.modify_date AS ModificationDate,
 OBJECT_DEFINITION(object_id) AS ObjectDefinition
 FROM sys.objects o
 WHERE 
 ((o.type IN ('AF', 'FN', 'IF', 'P', 'TF', 'TT', 'U', 'V', 'X') AND @chrObjectType IS NULL) OR o.type = @chrObjectType)
 AND OBJECT_DEFINITION(o.object_id) LIKE '%' + @chvStringToFind + '%'
 ) AS t
 ORDER BY TypeDescription, Name

您可以将其脚本化并搜索脚本。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM