Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Find all Stored Procedures having a given text in it

4.86/5 (4 votes)
11 Oct 2011CPOL 9.1K  
We use a slightly modified approach that returns results from more than stored procedures (although it could be modified to return only results for stored procedures). We use this code in a stored procedure that requires a parameter containing the text to search for.@StringToFind...
We use a slightly modified approach that returns results from more than stored procedures (although it could be modified to return only results for stored procedures). We use this code in a stored procedure that requires a parameter containing the text to search for.

SQL
@StringToFind VarChar(7998)

AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @LikeSearch VarChar(8000)
    SET @LikeSearch = '%' + @StringToFind + '%'

    SELECT Distinct SO.Name
        ,CASE SO.Type
            WHEN 'C' THEN 'CHECK constraint'
            WHEN 'D' THEN 'Default or DEFAULT constraint'
            WHEN 'F' THEN 'FOREIGN KEY constraint'
            WHEN 'FN' THEN 'Scalar function'
            WHEN 'IF' THEN 'In-lined table-function'
            WHEN 'K' THEN 'PRIMARY KEY or UNIQUE constraint'
            WHEN 'L' THEN 'Log'
            WHEN 'P' THEN 'Stored procedure'
            WHEN 'R' THEN 'Rule'
            WHEN 'RF' THEN 'Replication filter stored procedure'
            WHEN 'S' THEN 'System table'
            WHEN 'TF' THEN 'Table function'
            WHEN 'TR' THEN 'Trigger'
            WHEN 'U' THEN 'User table'
            WHEN 'V' THEN 'View'
            WHEN 'X' THEN 'Extended stored procedure'
            ELSE 'Unidentified' END AS Type
        ,@StringToFind AS SearchedFor
        ,Definition AS SearchedIn
        ,CHARINDEX(@StringToFind, definition, 0) AS PositionWhereFound
        ,LEN(definition) AS TextLength
    FROM sysobjects SO (NOLOCK)
       INNER JOIN sys.sql_modules SM (NOLOCK) on SO.Id = SM.object_id
       AND SM.Definition LIKE @LikeSearch
    ORDER BY Type,SO.Name

END



Why the 7998 size designation? VarChar has a limit of 8000 characters and we need to add '%' to both the front and back of the string for the LIKE functionality to work.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)