Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

I want to search for a text from all my database stored procedures. I use the below SQL:

SELECT DISTINCT

       o.name AS Object_Name,

       o.type_desc

  FROM sys.sql_modules m

       INNER JOIN

       sys.objects o

         ON m.object_id = o.object_id

 WHERE m.definition Like '%[ABD]%';

I want to search for [ABD] in all stored procedures including square brackets, but it's not giving the proper result. How can I change my query to achieve this?

2 Answers

0 votes
by (40.7k points)

In this case, ESCAPE the square brackets. Now, the square brackets will be considered as string literals, not as the wild cards.

WHERE m.definition Like '%\[ABD\]%' ESCAPE '\'

You can learn in-depth about SQL statements, queries and become proficient in SQL queries by enrolling in our industry-recognized SQL training online.

0 votes
by (36.7k points)

To search for a specific text pattern, including square brackets, within all stored procedures in SQL Server, the query needs to be adjusted to handle the special characters in the search pattern correctly, as the previous query is able to search the ABD characters but the modifications are to be made in such a way so that the brackets can also be a part of the pattern matching ‘[‘,’]’, This can happen by using the Escape character in the starting of the bracket and after the ending of the characters  ABD so, that they can be treated as a literal character in the search pattern, In SQL server, to search for special characters like square brackets, you need to use the character ‘\’ before them.

Here’s how you can modify your query to search for the text ‘[ABD]’ including the square brackets:

SELECT DISTINCT

       o.name AS Object_Name,

       o.type_desc

FROM sys.sql_modules m

INNER JOIN sys.objects o

    ON m.object_id = o.object_id

WHERE m.definition LIKE '%\[ABD\]%';

...