31

I am trying to escape the underscore character in a LIKE Statement. I have tried to use the ESCAPE keyword as follows:

COLUMNNAME NOT LIKE '%[\_]xyz%' ESCAPE '\'

but it doesn't work. It is still filtering out %xyz% when I really want it to filter out %_xyz%.

If not by the ESCAPE keyword, how else can this be accomplished?

Any help is appreciated.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
James Thomas
  • 743
  • 1
  • 5
  • 9

3 Answers3

46

Just this should work:

COLUMNNAME NOT LIKE '%[_]xyz%'

You don't need the ESCAPE here. What you wrote should also work.

If you do want to use ESCAPE you could do this:

columnname NOT LIKE '%\_xyz%' ESCAPE '\';

Documentation on escape characters is here.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
16

use brakets [_]

This works for me in SQL Server 2005

select *
from #table 
where a like '%[_]xyz%'
Jose Chama
  • 2,948
  • 17
  • 22
  • +1: Supporting link: http://sqlserver2000.databases.aspfaq.com/how-do-i-search-for-special-characters-e-g-in-sql-server.html – OMG Ponies Feb 20 '10 at 00:04
5

Try it without the brackets:

COLUMNNAME NOT LIKE '%\_xyz%' ESCAPE '\'
Guffa
  • 687,336
  • 108
  • 737
  • 1,005