Search for Text in All Stored Procedures SQL Server
When managing a SQL Server database, developers and database administrators often need to locate specific text within stored procedures. Practically speaking, whether you are searching for a table name, a column reference, or a particular SQL keyword, finding the right information quickly can save hours of manual work. This full breakdown explains how to search for text in all stored procedures SQL Server using several reliable methods, including T‑SQL queries, built‑in system views, and third‑party tools. You will learn step by step how to write efficient search queries, understand the underlying metadata, and avoid common pitfalls that lead to incomplete or inaccurate results.
Why Searching Stored Procedures Matters
Stored procedures are the backbone of most SQL Server applications. They encapsulate business logic, enforce data integrity, and improve performance through precompiled execution plans. Even so, as databases grow and evolve, stored procedures can become difficult to maintain. A simple rename of a table or column can break dozens of procedures, and without a proper search strategy, identifying affected code becomes a time‑consuming nightmare Not complicated — just consistent. Took long enough..
Searching for text in all stored procedures SQL Server also helps with:
- Impact analysis before schema changes
- Security audits to detect sensitive data handling
- Code reviews to enforce coding standards
- Debugging to trace logic errors or unexpected behavior
Understanding SQL Server Metadata for Stored Procedures
Before diving into search techniques, You really need to understand where SQL Server stores information about stored procedures. The primary sources are:
- sys.sql_modules – Contains the definition text of all SQL modules, including stored procedures, functions, and views.
- sys.procedures – Lists all stored procedures in the database.
- INFORMATION_SCHEMA.ROUTINES – A standard view that includes routine names and types.
The sys.sql_modules view is the most commonly used source because it includes the full definition of each module in the definition column. This column holds the actual T‑SQL code, making it ideal for text searches Not complicated — just consistent..
Method 1: Using sys.sql_modules for Text Search
The simplest and most direct way to search for text in all stored procedures SQL Server is by querying the sys.sql_modules view. Here is a basic example:
SELECT
OBJECT_NAME(object_id) AS ProcedureName,
definition AS ProcedureDefinition
FROM sys.sql_modules
WHERE definition LIKE '%YourSearchText%'
Replace YourSearchText with the term you want to find. To give you an idea, if you are looking for references to a table named Orders, your query would be:
SELECT
OBJECT_NAME(object_id) AS ProcedureName,
definition AS ProcedureDefinition
FROM sys.sql_modules
WHERE definition LIKE '%Orders%'
This query returns the name and full definition of every stored procedure that contains the word Orders. While effective, it can return a large amount of data, especially in databases with many procedures.
Method 2: Filtering by Object Type
To narrow down the results specifically to stored procedures, you can join sys.sql_modules with sys.procedures:
SELECT
p.name AS ProcedureName,
m.definition AS ProcedureDefinition
FROM sys.sql_modules m
INNER JOIN sys.procedures p ON m.object_id = p.object_id
WHERE m.definition LIKE '%YourSearchText%'
This approach ensures that only stored procedures are included in the results, excluding functions, triggers, and views that may also appear in sys.sql_modules.
Method 3: Using OBJECT_DEFINITION Function
Another powerful technique involves the OBJECT_DEFINITION function, which returns the definition of a specified object. You can combine it with a cursor or a dynamic query to iterate through all stored procedures:
DECLARE @ProcedureName NVARCHAR(256)
DECLARE @Definition NVARCHAR(MAX)
DECLARE proc_cursor CURSOR FOR
SELECT name FROM sys.procedures
OPEN proc_cursor
FETCH NEXT FROM proc_cursor INTO @ProcedureName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Definition = OBJECT_DEFINITION(OBJECT_ID(@ProcedureName))
IF @Definition LIKE '%YourSearchText%'
BEGIN
PRINT @ProcedureName
END
FETCH NEXT FROM proc_cursor INTO @ProcedureName
END
CLOSE proc_cursor
DEALLOCATE proc_cursor
While this method provides precise control, it is generally slower than querying sys.sql_modules directly due to the overhead of looping through each procedure Most people skip this — try not to. That alone is useful..
Method 4: Searching with INFORMATION_SCHEMA.ROUTINES
For those who prefer standard SQL views, the INFORMATION_SCHEMA.ROUTINES view can be used in combination with ROUTINE_DEFINITION:
SELECT
ROUTINE_NAME,
ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
AND ROUTINE_DEFINITION LIKE '%YourSearchText%'
This method is portable across different database systems but may not capture all procedures if the ROUTINE_DEFINITION column is truncated in certain SQL Server versions.
Advanced Search Techniques
For more complex searches, consider using full‑text indexing or regular expressions. While SQL Server does not natively support regular expressions in LIKE clauses, you can use the PATINDEX function for pattern matching:
SELECT
OBJECT_NAME(object_id) AS ProcedureName,
definition AS ProcedureDefinition
FROM sys.sql_modules
WHERE PATINDEX('%YourPattern%', definition) > 0
Additionally, enabling full‑text search on system tables can significantly improve performance for large databases.
Best Practices for Efficient Searches
To ensure your searches are both accurate and performant, follow these best practices:
- Use specific search terms to reduce false positives and improve result relevance.
- Limit result sets with additional filters such as schema name or creation date.
- Avoid leading wildcards in
LIKEclauses, as they prevent index usage and slow down queries. - Test queries on a development environment before running them on production databases.
- Document search results for future reference and audit purposes.
Common Pitfalls and How to Avoid Them
One of the most common mistakes is assuming that LIKE searches are case‑sensitive. By default, SQL Server uses case‑insensitive collation, which means searching for orders will also match Orders. If case sensitivity is required, use the COLLATE clause:
WHERE m.definition LIKE '%Orders%' COLLATE SQL_Latin1_General_CP1_CS_AS
Another pitfall is searching for partial words, which can return irrelevant results. Take this: searching for Order might also match OrderDetails or Reorder. To avoid this, use word boundaries or more specific search terms Surprisingly effective..
Conclusion
Searching for text in all stored procedures SQL Server is a fundamental skill for any database professional. sql_modulesandsys.Whether you choose simple LIKE queries, joins with object metadata, or advanced pattern matching, the key is to understand your data and tailor your approach accordingly. By leveraging system views like sys.procedures, you can quickly locate references to tables, columns, or keywords across your entire database. With the techniques outlined in this guide, you will be well equipped to perform efficient and accurate searches, ensuring your database remains maintainable, secure, and aligned with your application’s evolving needs.
And yeah — that's actually more nuanced than it sounds.
Automating and Extending Procedure Searches
1. Encapsulating Search Logic in a Reusable Stored Procedure
Creating a dedicated procedure eliminates the need to rewrite the same WHERE clauses over and over. And the following example, dbo. Now, searchProcedureDefinitions, accepts a search term, optional schema filter, and a flag to enforce case‑sensitivity. It also supports pagination via OFFSET/FETCH to keep result sets manageable.
CREATE OR ALTER PROCEDURE dbo.SearchProcedureDefinitions
@SearchTerm NVARCHAR(500),
@SchemaName SYSNAME = NULL, -- optional schema filter
@CaseSensitive BIT = 0, -- 0 = use collation, 1 = force CS
@PageNumber INT = 1,
@PageSize INT = 100,
@IncludeDefinitions BIT = 1 -- 0 = return only object names
AS
BEGIN
SET NOCOUNT ON;
-- Build the LIKE expression
DECLARE @LikePattern NVARCHAR(500) = '%' + @SearchTerm + '%';
DECLARE @CollationExpr NVARCHAR(100) = '';
IF @CaseSensitive = 1
SET @CollationExpr = ' COLLATE SQL_Latin1_General_CP1_CS_AS';
ELSE
SET @CollationExpr = '';
DECLARE @SQL NVARCHAR(MAX) = N'
SELECT ' + CASE WHEN @IncludeDefinitions = 1 THEN
N' p.name AS ProcedureName, s.But name AS SchemaName, m. definition AS Definition '
ELSE
N' p.Think about it: name AS ProcedureName, s. name AS SchemaName '
END + N'
FROM sys.Practically speaking, sql_modules m
INNER JOIN sys. Because of that, procedures p ON p. object_id = m.object_id
INNER JOIN sys.schemas s ON s.schema_id = p.schema_id
WHERE ' + QUOTENAME('s') + '.That said, ' + QUOTENAME('name') + COALESCE(N' = @Schema', N' IS NOT NULL') + N'
AND m. Here's the thing — definition ' + CASE WHEN @CaseSensitive = 1 THEN
N'LIKE @Pattern' + @CollationExpr + N'
OR PATINDEX(@Pattern, m. definition) > 0'
ELSE
N'LIKE @Pattern' + N'
OR PATINDEX(@Pattern, m.definition) > 0'
END + N'
ORDER BY p.
EXEC sp_executesql
@SQL,
N'@Schema SYSNAME, @Pattern NVARCHAR(500), @OffsetRows INT, @FetchRows INT',
@Schema = @SchemaName,
@Pattern = @LikePattern,
@OffsetRows = (@PageNumber - 1) * @PageSize,
@FetchRows = @PageSize;
END;
GO
Usage example
EXEC dbo.SearchProcedureDefinitions
@SearchTerm = 'Customer',
@SchemaName = 'dbo',
@CaseSensitive = 0,
@PageNumber = 1,
@PageSize = 50;
2. Leveraging Full‑Text Search for Massive Codebases
When the total size of sys.sql_modules.Practically speaking, definition exceeds a few megabytes, LIKE scans become expensive. SQL Server’s full‑text search can dramatically speed up keyword lookups.
-
Create a full‑text catalog (once per database):
CREATE FULLTEXT CATALOG ftc_ProcedureDefs AS DEFAULT; -
Add the
sys.sql_modulescolumn to the catalog:CREATE FULLTEXT INDEX ON sys.sql_modules (definition