举例说明:

例如我们要进行模糊查询:



--测试数据

declare @tablea table (id int ,col varchar(20))

insert into @tablea

select 1,'maco' union all

select 2,'mao' union all

select 3,'micro'


--模糊查询

select * from @tablea where col like '%ma%'


/*结果

id col

----------- --------------------

1 maco

2 mao

*/



这是最普通的模糊查询了

但是当col列含有特殊字符例如%%的时候



declare @tableb table (id int ,col varchar(20))

insert into @tableb

select 1,'m%a%co' union all

select 2,'m%a%o' union all

select 3,'miacro'


select * from @tableb where col like '%%a%%'


上面这句就不行了,结果相当于%a%,有a的都出来了

/*

结果:

id col

----------- --------------------

1 m%a%co

2 m%a%o

3 miacro

*/


此时我们可以用escape来处理


declare @tablec table (id int ,col varchar(20))

insert into @tablec

select 1,'m%a%co' union all

select 2,'m%a%o' union all

select 3,'miacro'


--模糊查询

select * from @tablec where col like '%$%a$%%' escape '$'

/*结果

id col

----------- --------------------

1 m%a%co

2 m%a%o

*/