escape在sqlserver中的使用--【叶子】

本文详细介绍了在SQL Server中使用Escape关键字处理模糊查询时遇到的特殊字符问题。通过具体的例子展示了如何正确使用Escape避免因特殊字符导致的查询错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

escapesqlserver中的使用--【叶子】

1escape是干什么用的?

escape相对于转移字符

2escape在什么情况下使用?

举例说明:

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

--测试数据

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

*/

@【叶子】http://blog.youkuaiyun.com/maco_wang 原创作品,转贴请注明作者和出处,留此信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值