MS_SQL模糊查询like和charindex的对比

like查询效率低下,网上搜了一下替代like查询的方法,都是说用charindex方法,自己对比了一下查询速度

test1表中有一千两百多万条数据,我只给ID加了索引

先看一下 '%我%'这种模糊查询:

declare @q datetime
set @q = getdate()
select ID,U_Name,U_Sex,U_Age,U_Address from test1 where U_Name like '%我%'
select [like执行花费时间(毫秒)]=datediff(ms,@q,getdate())

declare @w datetime
set @w = getdate()
select ID,U_Name,U_Sex,U_Age,U_Address from test1 where charindex('',U_Name) >0
select [charindex执行花费时间(毫秒)]=datediff(ms,@w,getdate())

查询结果:

两者的时间差不多,不过要是在千万、乃至上亿的数据中还是能明显感觉到两者的查询速度吧。

再看下'我%'这种的模糊查询:

declare @q datetime
set @q = getdate()
select ID,U_Name,U_Sex,U_Age,U_Address from test1 where U_Name like '我%'
select [like执行花费时间(毫秒)]=datediff(ms,@q,getdate())

declare @w datetime
set @w = getdate()
select ID,U_Name,U_Sex,U_Age,U_Address from test1 where charindex('',U_Name) >0
select [charindex执行花费时间(毫秒)]=datediff(ms,@w,getdate())

查询结果:

次奥!谁说charindex的效率比like高的?砍你丫的!

所以需要在不同条件下选择两种模糊查询,'%我%'这种的就用charindex,'我%'这种的就用like!

转载于:https://www.cnblogs.com/New-world/archive/2012/11/28/2793560.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值