Home > Scripts, Sql Server, Stored Procedure > How to find all the Stored Procedures having a given text in it?

How to find all the Stored Procedures having a given text in it?

Recently, I was needed to search for all the Stored Procedures having a given text in its definition. So, as usual did the g :) :) gling,  most of the top results returned were suggesting to use INFORMATION_SCHEMA.ROUTINES view like below, which is not going to return correct result in all the scenario’s:

SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%SearchString%'
AND ROUTINE_TYPE='PROCEDURE'

As usual tried to understand the query and thought of checking it’s correctness. And to my surprise when I checked this view’s definition using: sp_helptext ‘INFORMATION_SCHEMA.ROUTINES’,  the ROUTINE_DEFINITION column was returning only the first 4000 characters of the Stored Procedure definition  i.e. in view ROUTINE_DEFINITION column is defined as: convert(nvarchar(4000),object_definition(o.object_id))AS ROUTINE_DEFINITIONSo with this it is clear that it will not return all the Stored Procedure’s which have the first occurrence of the search sting in its definition after 4000 characters.

 To get correct results we can use sys.procedures view as below, as the return type of the function OBJECT_DEFINITION(object_id) which returns Stored Procedure definition is of type nvarchar(max):

SELECT OBJECT_NAME(object_id), OBJECT_DEFINITION(object_id)
 FROM sys.procedures
 WHERE OBJECT_DEFINITION(object_id) LIKE '%SearchString%'

Below screen shot illustrates the difference between these two queries:

There are multiple alternative way’s with which we can correctly find all the Stored Procedure’s having a given text. And sys.procedures explained in this article is one such solution.

Please correct me, if my understanding is wrong. Comments are always welcome.

  1. October 1, 2011 at 5:36 PM | #1

    Wow, that’s crazy that ROUTINE_DEFINITION only gets the first 4000 characters! Any idea as to why they would implement it so? Pretty much everyone (including myself which I believe was one of your sources: http://devblog.grinn.net/2008/02/search-for-stored-procedure-containing.html) uses ROUTINE_DEFINITION to perform such a query, so this is a big find, Basavaraj!

  2. Maurice Pelchat
    October 4, 2011 at 6:30 AM | #2

    Do you know view sys.Sql_modules?

    Select object_name(object_id), definition
    From sys.sql_modules
    Where definition like ‘%searchstring%’ and objectpropertyex(object_id, ‘isProcedure’)=1

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s