views:

7569

answers:

4

How do I escape a string in SQL Server's stored procedure so that it is safe to use in LIKE expression.

Suppose I have an NVARCHAR variable like so:

declare @myString NVARCHAR(100);

And I want to use it in a LIKE expression:

... WHERE ... LIKE '%' + @myString + '%';

How do I escape the string (more specifically, characters that are meaningful to LIKE pattern matching, e.g. '%' or '?') in T-SQL, so that it is safe to use in this manner?

For example: given @myString = 'aa%bb' I want WHERE ... LIKE '%' + @somehowEscapedMyString + '%' to match 'aa%bb', 'caa%bbc' but not 'aaxbb' or 'caaxbb'.

+3  A: 

You specify the escape character. Documentation here:
http://msdn.microsoft.com/en-us/library/ms179859.aspx

Corey Trager
I was wishing for something that already nows what needs to be escaped in a LIKE expression.
The answer suggested you specify your own escape character so "meaningful " characters will not be meaningful anymore.
Goran
+1  A: 

Do you want to look for strings that include an escape character? For instance you want this:

select * from table where myfield like '%10%%'.

Where you want to search for all fields with 10%? If that is the case then you may use the ESCAPE clause to specify an escape character and escape the wildcard character.

select * from table where myfield like '%10!%%' ESCAPE '!'
Vincent Ramdhanie
I added an example of what I want to the question.
+7  A: 

To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)

For example this escapes the % symbol, using \ as the escape char:

select * from table where myfield like '%15\% off%' ESCAPE '\'

If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:

set @myString = replace( 
                replace( 
                replace( 
                replace( @myString
                ,    '\', '\\' )
                ,    '%', '\%' )
                ,    '_', '\_' )
                ,    '[', '\[' )

(Note that you have to escape your escape char too). Then you can use something like this:

select * from table where myfield like '%' + @myString + '%' ESCAPE '\'

Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.

Rory
+1  A: 

Had a similar problem (using NHibernate, so the ESCAPE keyword would have been very difficult) and solved it using the bracket characters. So your sample would become

WHERE ... LIKE '%aa[%]bb%'

If you need proof:

create table test (field nvarchar(100))
go
insert test values ('abcdef%hijklm')
insert test values ('abcdefghijklm')
go
select * from test where field like 'abcdef[%]hijklm'
go
Dries Van Hansewijck