Escaping From An Underscore In A SQL Server Wildcard / LIKE Search


There are two different ways to perform a wildcard (aka LIKE) search in SQL Server to find a word with an “_” underscore. Both options are outlined at the end of the article after a reference to the cult classic Mystery Science Theater 3000: Escape From The Bronx.

What the heck?!? SQL Server’s wildcard search is broken! I was writing a query against sys.sql_modules to find any objects which were referencing the view “v_customer” via a linked server:

SELECT OBJECT_NAME(sm.object_id)
FROM sys.sql_modules AS sm
WHERE sm.definition LIKE '%v_customer%'

A number of objects were returned which didn’t seem to have the view in them. After running the same query a few times hoping for a different result (surprisingly that didn’t work) I put my thinking cap on. Somewhere deep in the bowels of my brain (can a brain have bowels?) I recalled that an underscore is actually a wildcard character in SQL Server 2000, SQL Server 2005, SQL Server 2008, and onward.

So, how do you do a wildcard query to look for a word or phrase with an underscore? You must escape! (As in Escape From The Bronx! The first Mystery Science Theater 3000 movie I ever saw.  I was rolling on the ground laughing. You gotta check this thing out.)

Maybe he can get a haircut after he escapes?
Maybe he can get a haircut after he escapes?

If you need to perform a wildcard search for a term with an underscore there are two options.  For the first option ou can enclose the underscore with square brackets like the following example:

SELECT OBJECT_NAME(sm.object_id)
FROM sys.sql_modules AS sm
WHERE sm.definition LIKE '%v[_]customer%'

The second option is to actually declare what the escape character will be using the following syntax:

SELECT OBJECT_NAME(sm.object_id)
FROM sys.sql_modules AS sm
WHERE sm.definition LIKE '%v|_customer%' ESCAPE '|'

Using this syntax tells SQL Server to “escape” the character immediately following the declared escape character. The example above will work just as well if the vertical pipe was replaced with a different character, an ampersand for example.

SELECT OBJECT_NAME(sm.object_id)
FROM sys.sql_modules AS sm
WHERE sm.definition LIKE '%v&_currency%' ESCAPE '&'

So if you want to escape from the Bronx or from an _ you’ve got multiple options.

 

Props to the wizards who patrol stackoverflow for the original source of this information!

 

 

 


Leave a Reply

Your email address will not be published.