SqlServer之like、charindex、patindex

来源:互联网 发布:smtp.qq. 端口号 编辑:程序博客网 时间:2024/04/29 20:31

 

 SqlServer之like、charindex、patindex


1、环境介绍
测试环境 SQL2005
测试数据 200W条


2、环境准备
2.1建表
CREATE TABLE [dbo].[Depratments](
        [Dep_id] [int] NOT NULL,
        [Dep_name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
2.2创建数据
create procedure ins_Depratments
as
        declare @n int;
        declare @title varchar(30);
        set @n =1;
        set @title='';
begin
        while @n<2000000
        begin
               -- set @title = (select case when (cast(floor(rand() * 6) as int)) =5 then '部门经理' else '职员'end);
                insert into Depratments (Dep_id,Dep_name) values (@n,'开发'+CAST(@n as varchar)) ;
               -- insert into employees values (@n,'刘备'+CAST(@n as varchar),'男',@title,
                       78000,'11110333x'+CAST(@n as varchar),@n,getdate());
               set @n=@n+1;
        end
end
2.3执行        exec ins_Depratments
 
3、场景
3.1前后都有百分号的查询
SET STATISTICS IO ON
set statistics time ON
go
select count(*) from depratments where Dep_name like '%开发1000%';
go 
select count(*) from depratments where charindex('开发1000',Dep_name)>0;
go
select count(*) from depratments where patindex('%开发1000%',Dep_name)>0;
go
无索引的情况 charindex > patindex > like
        CPU 时间 = 4391 毫秒,占用时间 = 5322 毫秒。
        CPU 时间 = 3812 毫秒,占用时间 = 4690 毫秒。
        CPU 时间 = 4047 毫秒,占用时间 = 5124 毫秒。
带索引的情况 charindex > patindex > like
       CPU 时间 = 4297 毫秒,占用时间 = 4535 毫秒。
       CPU 时间 = 3844 毫秒,占用时间 = 4024 毫秒。
       CPU 时间 = 4219 毫秒,占用时间 = 4351 毫秒。
结论:
当前后都使用百分号的情况(%string%),①charindex性能稍微好点,like、patindex性能相近;②索引在这种情况中失效
 

3.2百分号在后面的查询
SET STATISTICS IO ON
set statistics time ON
go
select count(*) from depratments where Dep_name like '开发1000%';
go
select count(*) from depratments where charindex('开发1000',Dep_name)>0;
go
select count(*) from depratments where patindex('开发1000%',Dep_name)>0;
go
 
无索引的情况 patindex > like > charindex
        CPU 时间 = 844 毫秒,占用时间 = 1465 毫秒。
        CPU 时间 = 3875 毫秒,占用时间 = 3914 毫秒。
        CPU 时间 = 968 毫秒,占用时间 = 969 毫秒。
 
带索引的情况  like > patindex > charindex
        CPU 时间 = 0 毫秒,占用时间 = 18 毫秒
        CPU 时间 = 3766 毫秒,占用时间 = 4026 毫秒。
        CPU 时间 = 937 毫秒,占用时间 = 983 毫秒。
结论:
无索引的情况,patindex的性能最佳,是charindex性能的4倍
带索引的情况,like的性能最佳
 
总结:
①索引只适用于百分号在后面的情况(string%)
②在前后都是百分号的情况下charindex 的性能最佳
③百分号在后面的查询,无索引的情况,patindex的性能最佳

 

 

 

 

原创粉丝点击