您的位置:首页 > 其它

escape在什么情况下使用

2012-07-16 11:15 197 查看
举例说明:

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

--测试数据

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

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: