查看Sql语句执行速度


原文链接:http://www.cnblogs.com/New-world/archive/2012/11/28/2793560.html

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!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM