Tell Us About Your Business

Your name:
Business name:
E-mail address:
Phone number:
Comments or questions:
Subscribe to our newsletter:
Tickets |  Project Management |  207-347-7360

Search

Popular Tags

Archive

About Dirigo

Dirigo's roots are in retail, catalog, television and radio direct response marketing. We're responsible for multi-million dollar web businesses. Whether its sharing our experience and expertise or helping connect you to some of the best thinkers in our industry, we dig deep to find opportunities that drive revenue.

Escaping percent and underscore characters in t sql like clause

July 21 / Ivan Sokolovich, Sr. Tech

In T-SQL we normally use a like clause to search for patterns. The following:

select *
from table
where column like '%pattern%'

will return all the rows of the table which contain <pattern> in them. The percent sign is used as the placeholder for any number of characters in the string.

The above query will match any of the below strings:

  • testpattern
  • pattern
  • patterntest
  • testpatterntest

Similarly, the underscore character will match any single character of the string. The following:

select *
from table
where column like '%pattern_'

will match only the strings with a single character following the pattern, such as:

  • testpattern1
  • pattern1

but not

  • testpattern1test

But, if you are searching for the actual underscore or percent character within a string you should use the T-SQL escape sequence [%] or [_].

If you want to find the string test_string%, then your T-SQL like clause would look like the following:

select *
from table where column like 'test[_]string[%]'

P.S. If you want to match [ character, then you would use [[] syntaxis.