T-SQL Searching using Wildcard Characters

Searching for Wildcard Characters

You can search for wildcard characters. There are two methods for specifying a character that would ordinarily be a wildcard:

Use the ESCAPE keyword to define an escape character. When the escape character is placed in front of the wildcard in the pattern, the wildcard is interpreted as a character. For example, to search for the string 5% anywhere in a string, use:

WHERE ColumnA LIKE '%5/%%' ESCAPE '/'
In this LIKE clause, the leading and ending percent signs (%) are interpreted as wildcards, and the percent sign preceded by a slash (/) is interpreted as the % character.

Use square brackets ([ ]) to enclose the wildcard by itself. To search for a hyphen (-), instead of using it to specify a search range, use the hyphen as the first character inside a set of brackets:

WHERE ColumnA LIKE '9[-]5'
The following table shows the use of wildcards enclosed in square brackets.

Symbol Meaning
LIKE '5[%]'
5%

LIKE '5%'
5 followed by any string of 0 or more characters

LIKE '[_]n'
_n

LIKE '_n'
an, in, on (and so on)

LIKE '[a-cdf]'
a, b, c, d, or f

LIKE '[-acdf]'
-, a, c, d, or f

LIKE '[ [ ]'
[

LIKE ']'
]

When string comparisons are performed with LIKE, all characters in the pattern string are significant, including every leading and trailing blank (space). If a comparison to return all rows with a string LIKE 'abc ' (abc followed by a single space) is requested, a row in which the value of that column is abc (abc without a space) is not returned. The reverse, however, is not true. Trailing blanks in the expression to which the pattern is matched are ignored. If a comparison to return all rows with a string LIKE 'abc' (abc without a space) is requested, all rows that start with abc and have zero or more trailing blanks are returned.

 

Comments are closed.

Post Navigation