日期:2014-05-18  浏览次数:20547 次

patindex函数 和 like的查询效率
SQL code

select * from data0001 where patindex('%b%',curr_code)>0
和
select * from data0001 where curr_code like '%b%'
哪条效率高,讲出理由。




------解决方案--------------------
如果 curr_code 上有 索引

select * from data0001 where curr_code like '%b%'--不会用到索引
select * from data0001 where curr_code like 'b%'--会用到索引
------解决方案--------------------
SQL code
一、测试环境: 
1。数据库:Sql Server 2008 
2。测试表:15000记录,char类型主键,无其他索引 
3。测试字段:ntext 类型,最大数据长度12000 
二、测试语句: 
1。select * from ProductTemp where ProductDesc like '%192.168.70.236%' 
2。select * from ProductTemp where charindex('192.168.70.236',ProductDesc)>0 
3。select * from ProductTemp where patindex('%192.168.70.236%',ProductDesc)>0
三、测试结果: 
1。效率测试结果: charindex > like > patindex ,效率差大概20% 
2。适用性测试结果: 
1)charindex对于检索结果最大位移有要求,经测试,Sql2008中的ntext字段,位移不能超过3987,否则返回0; 
2)patindex 和 like 无位移限制; 
3)patindex 支持匹配表达式,可以应用正则; 
4)like可以用'%oldstring%'进行模糊匹配; 
5)charindex只能匹配固定字符串