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的性能最佳


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM