1

Sql where statement with = works but LIKE does not Is there a fix for this?

Here is the exact code:

create table zSyn (xField nvarchar(255));
insert into zSyn(xField)
select 'DEVCON 5 Minute Epoxy amber [1:1]';

--Works and returns 1 row:
select * from zSyn
where xField = 'DEVCON 5 Minute Epoxy amber [1:1]';

--Does NOT return any rows:
select * from zSyn
where xField like '%' + 'DEVCON 5 Minute Epoxy amber [1:1]' + '%'
Remy
  • 407
  • 3
  • 17

4 Answers4

6

You need to escape []:

select * from zSyn
where xField like ('%' + 'DEVCON 5 Minute Epoxy amber ![1:1!]' + '%') ESCAPE '!';

db<>fiddle demo

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
2

The problem is that the square braces represent character classes in SQL Server like. One method is to use escape. Here are two other options:

xField like '%' + 'DEVCON 5 Minute Epoxy amber [[]1:1]' + '%'
xField like '%' + 'DEVCON 5 Minute Epoxy amber _1:1_' + '%'

The second will match any character, including a square brace. That is probably okay for your purposes.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

Just another option if you want to avoid the need to escape the string is to use charindex()

Example

Select * 
 From  zSyn
 Where charindex('DEVCON 5 Minute Epoxy amber [1:1]',xField)>0
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66
0

It could be that the square brackets are messing with LIKE because you can sometimes use square brackets for finding numerical or alphabetic characters i.e. LIKE ([A-Z])

SELECT * FROM zSyn WHERE xField LIKE ('%DEVCON 5 Minute Epoxy amber %1:1%')
russ
  • 579
  • 3
  • 7