Explain Codes LogoExplain Codes Logo

Search text in stored procedure in SQL Server

sql
search-engineering
sql-queries
database-management
Anton ShumikhinbyAnton Shumikhin·Nov 3, 2024
TLDR

Here's a speedy way to locate text within stored procedures:

SELECT OBJECT_NAME(object_id) FROM sys.sql_modules WHERE definition LIKE '%YourText%'

In this query, replace %YourText% with the text you're hunting. It returns the names of any stored procedures where your text appears.

Searching with special characters

When your search term contains special characters like [ or ], you need to escape them to carry out an accurate search. This becomes super handy if your clue leads to [ABD]. The SQL query for this is:

SELECT OBJECT_NAME(object_id) FROM sys.sql_modules WHERE definition LIKE '%\[ABD\]%' ESCAPE '\'

This piece of code basically entails ESCAPE '\', telling SQL to treat the backslash \ as an escape character. Consequently, you're in for an exact string search for [ABD].

Taking a closer look into stored procedures

To dig deeper into the content of stored procedures, use OBJECT_DEFINITION encompassed within sys.procedures. You might call this SQL archeology.

SELECT name, OBJECT_DEFINITION(object_id) FROM sys.procedures WHERE OBJECT_DEFINITION(object_id) LIKE '%YourText%'

This query compiles both the procedure names and their definitions. It's a double whammy in searching for your required text.

Third-party tools to the rescue

Can't seem to catch the culprit? Then it's time for outside help with tools like ApexSQL Search or the SSMS Tools Pack. These units provide superior features including an enhanced UI and the ability to find special characters with minimal resistance.

Exploring views and functions

Extend your search to views and user-defined functions. To search within views, use sys.views, and for functions, turn to INFORMATION_SCHEMA.ROUTINES.

-- Searching within views SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE VIEW_DEFINITION LIKE '%YourText%' -- Searching within functions SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_DEFINITION LIKE '%YourText%' AND ROUTINE_TYPE = 'FUNCTION'

With these queries, no corner of your SQL Server database remains unexplored.

Customizing searches for repeat actions

If your searches are a recurrent task, consider devising a custom stored procedure. Not only does it compile the search logic but it also enables a keyboard shortcut for a quick command. It's like having your personal genie in a lamp!

Moreover, a smart strategy can help highlight a keyword in your editor and invoke this search stored procedure with a shortcut, leading to instantaneous findings. It's all about mastering the craft of quick searches.