• SqlServer之like、charindex、patindex


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

  • 相关阅读:
    第四周:卷积神经网络 part3
    第四周作业:卷积神经网络学习part3
    视频学习--《 图像语义分割前沿进展》
    视频学习--《语义分割中的自注意力机制和低秩重建》
    第二次作业:卷积神经网络 part 1
    使用VGG模型迁移学习进行猫狗大战
    使用 VGG16 对 CIFAR10 分类
    CIFAR10 数据集分类
    MNIST数据集分类
    第一次作业:深度学习基础
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3102372.html
Copyright © 2020-2023  润新知