Sql Server How To Search Stored Procedures Text

6 min read

How to Search Stored Procedures Text in SQL Server: A Complete Guide

Searching through stored procedures text in SQL Server is a common requirement for database administrators, developers, and analysts who need to locate specific code, troubleshoot issues, or perform impact analysis. And whether you're looking for references to a particular table, function, or variable within your stored procedures, knowing how to efficiently search through procedure definitions can save hours of manual work. This thorough look explores multiple methods to search stored procedures text in SQL Server, from basic queries to advanced techniques.

Introduction to Searching Stored Procedures Text

When working with large databases containing hundreds or thousands of stored procedures, manually searching through each one becomes impractical. SQL Server provides several system views and functions that allow you to programmatically search through stored procedure definitions. The most commonly used approaches involve querying system catalog views like sys.sql_modules, INFORMATION_SCHEMA.ROUTINES, and using built-in functions such as OBJECT_DEFINITION().

Understanding these methods is crucial because they enable you to:

  • Quickly locate procedures that reference specific tables or columns
  • Identify procedures using deprecated functions or features
  • Perform security audits by finding procedures with dynamic SQL
  • Support migration projects by identifying compatibility issues

Method 1: Using sys.sql_modules System View

The sys.sql_modules system view is one of the most straightforward ways to search through stored procedures text. This view contains the definition of all SQL modules, including stored procedures, functions, and triggers.

Basic Search Syntax

SELECT 
    OBJECT_NAME(object_id) AS ProcedureName,
    definition AS ProcedureDefinition
FROM sys.sql_modules
WHERE definition LIKE '%SearchTerm%'

To give you an idea, to find all stored procedures that reference the Employees table:

SELECT 
    OBJECT_NAME(object_id) AS ProcedureName,
    definition AS ProcedureDefinition
FROM sys.sql_modules
WHERE definition LIKE '%Employees%'

Enhanced Search with Additional Information

You can enhance your search by including additional metadata about each procedure:

SELECT 
    SCHEMA_NAME(o.schema_id) AS SchemaName,
    OBJECT_NAME(sm.object_id) AS ProcedureName,
    o.create_date AS CreationDate,
    o.modify_date AS ModifiedDate,
    sm.definition AS ProcedureDefinition
FROM sys.sql_modules sm
INNER JOIN sys.objects o ON sm.object_id = o.object_id
WHERE o.type = 'P'  -- P indicates stored procedures
AND sm.definition LIKE '%SearchTerm%'
ORDER BY o.modify_date DESC

This approach provides valuable context including schema names, creation and modification dates, making it easier to identify recently changed procedures.

Method 2: Using INFORMATION_SCHEMA.ROUTINES

The INFORMATION_SCHEMA.ROUTINES view offers another approach to searching stored procedures text. While it doesn't contain the full definition, it includes a ROUTINE_DEFINITION column that can be searched.

SELECT 
    ROUTINE_SCHEMA AS SchemaName,
    ROUTINE_NAME AS ProcedureName,
    ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
AND ROUTINE_DEFINITION LIKE '%SearchTerm%'

Important limitation: The ROUTINE_DEFINITION column has a maximum length of 4000 characters. For procedures longer than this, you'll need to use the sys.sql_modules approach instead.

Method 3: Using OBJECT_DEFINITION Function

The OBJECT_DEFINITION() function returns the Transact-SQL source text of an object. When combined with system views, it allows for flexible searching:

SELECT 
    SCHEMA_NAME(o.schema_id) AS SchemaName,
    o.name AS ProcedureName,
    OBJECT_DEFINITION(o.object_id) AS ProcedureDefinition
FROM sys.objects o
WHERE o.type = 'P'
AND OBJECT_DEFINITION(o.object_id) LIKE '%SearchTerm%'

This method is particularly useful when you need to search for complex patterns or when working with specific object IDs Nothing fancy..

Advanced Search Techniques

Case-Insensitive Searches

By default, SQL Server searches are case-insensitive when using the default collation settings. On the flip side, you can explicitly control case sensitivity:

SELECT 
    OBJECT_NAME(object_id) AS ProcedureName,
    definition AS ProcedureDefinition
FROM sys.sql_modules
WHERE definition COLLATE SQL_Latin1_General_CP1_CS_AS LIKE '%SearchTerm%'

Searching for Multiple Terms

To search for procedures containing multiple terms, you can use multiple LIKE conditions:

SELECT 
    OBJECT_NAME(object_id) AS ProcedureName,
    definition AS ProcedureDefinition
FROM sys.sql_modules
WHERE (definition LIKE '%Term1%' OR definition LIKE '%Term2%')
AND definition LIKE '%CommonTerm%'

Using CONTAINS for Full-Text Search

For more advanced text searching capabilities, especially with large databases, consider using full-text indexing:

SELECT 
    OBJECT_NAME(object_id) AS ProcedureName,
    definition AS ProcedureDefinition
FROM sys.sql_modules
WHERE CONTAINS(definition, '"search term"')

Note that this requires setting up full-text indexing on the definition column first.

Practical Examples and Use Cases

Finding Procedures That Reference Specific Tables

One of the most common search scenarios involves locating procedures that interact with specific tables:

SELECT DISTINCT
    SCHEMA_NAME(o.schema_id) AS SchemaName,
    o.name AS ProcedureName,
    'References table: Sales' AS SearchResult
FROM sys.sql_modules sm
INNER JOIN sys.objects o ON sm.object_id = o.object_id
WHERE o.type = 'P'
AND (sm.definition LIKE '%Sales%' 
     OR sm.definition LIKE '%sales%')
ORDER BY SchemaName, ProcedureName

Locating Procedures with Dynamic SQL

Security-conscious database administrators often need to identify procedures using dynamic SQL:

SELECT 
    SCHEMA_NAME(o.schema_id) AS SchemaName,
    o.name AS ProcedureName,
    sm.definition AS ProcedureDefinition
FROM sys.sql_modules sm
INNER JOIN sys.objects o ON sm.object_id = o.object_id
WHERE o.type = 'P'
AND (sm.definition LIKE '%EXEC(%' 
     OR sm.definition LIKE '%EXECUTE(%'
     OR sm.definition LIKE '%sp_executesql%')

Searching for Deprecated Features

During database upgrades, you might need to find procedures using deprecated features:

SELECT 
    SCHEMA_NAME(o.schema_id) AS SchemaName,
    o.name AS ProcedureName
FROM sys.sql_modules sm
INNER JOIN sys.objects o ON sm.object_id = o.object_id
WHERE o.type = 'P'
AND (sm.definition LIKE '%TEXTPTR%'
     OR sm.definition LIKE '%UPDATETEXT%'
     OR sm.definition LIKE '%READTEXT%')

Performance Considerations

When searching through stored procedures text, performance can become an issue with large databases. Here are some optimization strategies:

Limit Results with TOP Clause

SELECT TOP 100
    OBJECT_NAME(object_id) AS ProcedureName,
    definition AS ProcedureDefinition
FROM sys.sql_modules
WHERE definition LIKE '%SearchTerm%'

Use EXISTS Instead of JOIN for Simple Checks

SELECT 
    SCHEMA_NAME(o.schema_id) AS SchemaName,
    o.name AS ProcedureName
FROM sys.objects o
WHERE o.type = 'P'
AND EXISTS (
    SELECT 1 
    FROM sys.sql_modules sm 
    WHERE sm.object_id = o.object_id 
    AND sm.definition LIKE '%SearchTerm%'
)

Create Indexes for Frequent Searches

Consider creating indexed views or computed columns for frequently searched terms to improve performance The details matter here..

Best Practices and Tips

1. Use Specific Search Terms

Instead of broad searches, use specific terms related to your objective:

-- Less effective
WHERE definition LIKE '%SELECT%'

-- More effective
WHERE definition LIKE '%SELECT%FROM%Employees%'

2. Combine Methods for Comprehensive Results

Different methods may return slightly different results due to character limits. Combining approaches ensures completeness:

SELECT DISTINCT
    COALESCE(OBJECT_NAME(object_id), ROUTINE_NAME) AS ProcedureName,
    'sys.sql_modules' AS Source
FROM sys.sql_modules
WHERE definition LIKE '%SearchTerm%'

UNION ALL

SELECT DISTINCT
    ROUTINE_NAME AS ProcedureName

```sql
SELECT DISTINCT
    ROUTINE_NAME AS ProcedureName,
    'sys.procedures' AS Source
FROM sys.procedures
WHERE OBJECT_DEFINITION(object_id) LIKE '%SearchTerm%';

This dual-source approach is useful because some older databases or migrated environments may store routine definitions differently across system views. By combining sys.Think about it: sql_modules and sys. procedures, you reduce the risk of missing procedures that exist in one catalog but not the other.

People argue about this. Here's where I land on it.

Final Thoughts

Effectively locating stored procedures that rely on dynamic SQL, deprecated features, or specific business logic requires a combination of metadata queries, thoughtful search patterns, and performance awareness. The examples provided here offer a starting point, but real-world implementations should account for database size, security constraints, and indexing strategies.

When conducting stored procedure audits, it is important to:

  • Test queries in a non-production environment first.
  • Use specific search terms whenever possible.
  • Validate results across multiple sources.
  • Monitor performance on large databases.

Conclusion

Searching through stored procedure definitions is a critical task for database administrators focused on security, optimization, and modernization. objects, and sys.With performance-conscious techniques like TOP, EXISTS, and indexed views, these searches can be executed efficiently. sql_modules, sys.procedures, teams can identify dynamic SQL usage, deprecated functionality, and problematic patterns. And by using system views such as sys. Adopting specific search terms and combining multiple query methods ensures comprehensive and accurate results.

Most guides skip this. Don't Simple, but easy to overlook..

In the long run, regular stored procedure reviews help maintain a clean, secure, and well-optimized SQL Server environment. The ongoing effort to locate and refactor procedures using dynamic SQL or deprecated features supports long-term database health and compliance.

Hot New Reads

Fresh from the Writer

More Along These Lines

Stay a Little Longer

Thank you for reading about Sql Server How To Search Stored Procedures Text. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home