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