原文鏈接: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!

