这是一个很久以前的例子,现在在整理资料时无意发现,就拿出来再改写分享。

1.需求

1.1 基本需求: 根据输入的地址关键字,搜索出完整的地址路径,耗时要控制在几十毫秒内。

1.2 数据库地址表结构和数据:

表TBAddress

表数据

1.3 例子:

e.g. 给出一个字符串如“广 大”,找出地址全路径中包含有“广” 和“大”的所有地址,結果如下:

下面将通过4个方法来实现,再分析其中的性能优劣,然后选择一个比较优的方法。

2.创建表和插入数据

2.1 创建数据表TBAddress

  1. use test;
  2. go
  3. /* create table */
  4. if object_id('TBAddress') is not null
  5. drop table TBAddress;
  6. go
  7. create table TBAddress
  8. (
  9. ID int ,
  10. Parent int not null ,
  11. LevelNo smallint not null ,
  12. Name nvarchar(50) not null ,
  13. constraint PK_TBAddress primary key ( ID )
  14. );
  15. go
  16. create nonclustered index ix_TBAddress_Parent on TBAddress(Parent,LevelNo) include(Name) with(fillfactor=80,pad_index=on);
  17. create nonclustered index ix_TBAddress_Name on TBAddress(Name)include(LevelNo)with(fillfactor=80,pad_index=on);
  18. go

create table

2.2 插入数据

  1. use test
  2. go
  3. /*insert data*/
  4. set nocount on
  5. Begin Try
  6. Begin Tran
  7. Insert Into TBAddress ([ID],[Parent],[LevelNo],[Name])
  8. Select 1,0,0,N'中国' Union All
  9. Select 2,1,1,N'直辖市' Union All
  10. Select 3,1,1,N'辽宁省' Union All
  11. Select 4,1,1,N'广东省' Union All
  12. ... ...
  13. Select 44740,930,4,N'奥依塔克镇' Union All
  14. Select 44741,932,4,N'巴音库鲁提乡' Union All
  15. Select 44742,932,4,N'吉根乡' Union All
  16. Select 44743,932,4,N'托云乡'
  17. Commit Tran
  18. End Try
  19. Begin Catch
  20. throw 50001,N'插入數據過程中發生錯誤.' ,1
  21. Rollback Tran
  22. End Catch
  23. go

附件:insert Data

 Note: 数据有44700条,insert代码比较长,所以采用附件形式。

3.测试,方法1

3.1 分析:

a. 先搜索出包字段Name中含有“广”、“大”的所有地址记录存入临时表#tmp。

b. 再找出#tmp中各个地址到Level 1的全路径。

c. 根据步骤2所得的结果,筛选出包含有“广”和“大”的地址路径。

d. 根据步骤3筛选的结果,查询所有到Level n(n为没有子地址的层编号)的地址全路径。

3.2 存储过程代码:

  1. Use test
  2. Go
  3. if object_ID('[up_SearchAddressByNameV0]') is not null
  4. Drop Procedure [up_SearchAddressByNameV0]
  5. Go
  6. create proc up_SearchAddressByNameV0
  7. (
  8. @Name nvarchar(200)
  9. )
  10. As
  11. set nocount on
  12. declare @sql nvarchar(max)
  13.  
  14. declare @tmp Table (Name nvarchar(50))
  15.  
  16. set @Name=@Name+' '
  17.  
  18. while patindex('% %',@Name)>0
  19. begin
  20. set @Name=replace(@Name,' ',' ')
  21. end
  22.  
  23. set @sql ='select ''' +replace(@Name,' ',''' union all select ''')+''''
  24. insert into @tmp(Name) exec(@sql)
  25.  
  26. if object_id('tempdb..#tmp') is not null drop table #tmp
  27. if object_id('tempdb..#') is not null drop table #
  28.  
  29. create table #tmp(ID int )
  30.  
  31. while @Name>''
  32. begin
  33. insert into #tmp(ID)
  34. select a.ID from TBAddress a where a.Name like '%'+substring(@Name,1,patindex('% %',@Name)-1)+'%'
  35.  
  36. set @Name=Stuff(@Name,1,patindex('% %',@Name),'')
  37. end
  38.  
  39. ;with cte_SearchParent as
  40. (
  41. select a.ID,a.Parent,a.LevelNo,convert(nvarchar(500),a.Name) as AddressPath from TBAddress a where exists(select 1 from #tmp x where a.ID=x.ID)
  42. union all
  43. select a.ID,b.Parent,b.LevelNo,convert(nvarchar(500),b.Name+'/'+a.AddressPath) as AddressPath
  44. from cte_SearchParent a
  45. inner join TBAddress b on b.ID=a.Parent
  46. --and b.LevelNo=a.LevelNo -1
  47. and b.LevelNo>=1
  48. )
  49. select a.ID,a.AddressPath
  50. into #
  51. from cte_SearchParent a
  52. where a.LevelNo=1 and exists(select 1 from @tmp x where a.AddressPath like '%'+x.Name+'%' having count(1)=(select count(1) from @tmp))
  53.  
  54. ;with cte_result as
  55. (
  56. select a.ID,a.LevelNo,b.AddressPath
  57. from TBAddress a
  58. inner join # b on b.ID=a.ID
  59. union all
  60. select b.ID,b.LevelNo,convert(nvarchar(500),a.AddressPath+'/'+b.Name) As AddressPath
  61. from cte_result a
  62. inner join TBAddress b on b.Parent=a.ID
  63. --and b.LevelNo=a.LevelNo+1
  64.  
  65. )
  66. select distinct a.ID,a.AddressPath
  67. from cte_result a
  68. where not exists(select 1 from TBAddress x where x.Parent=a.ID)
  69. order by a.AddressPath
  70. Go

procedure:up_SearchAddressByNameV0

3.3 执行查询:

  1. exec up_SearchAddressByNameV0 '广 大'

共返回195行记录。

3.4 客户端统计信息:

平均的执行耗时:  244毫秒

4.测试,方法2

方法2是参照方法1,并借助全文索引来优化方法1中的步骤1。也就是在name列上建立全文索引,在步骤1中,通过全文索引搜索出包字段Name中含有“广”、“大”的所有地址记录存入临时表#tmp,其他步骤保持不变。

4.1 创建全文索引

  1. use test
  2. go
  3. /*create fulltext index*/
  4. if not exists(select 1 from sys.fulltext_catalogs a where a.name='ftCatalog')
  5. begin
  6. create fulltext catalog ftCatalog As default;
  7. end
  8. go
  9. --select * From sys.fulltext_languages
  10. create fulltext index on TBAddress(Name language 2052 ) key index PK_TBAddress
  11. go
  12. alter fulltext index on dbo.TBAddress add(Fullpath language 2052)
  13. go

Note:  在Name列上创建全文索引使用的语言是简体中文(Simplified Chinese)

4.2 存储过程代码:

  1. Use test
  2. Go
  3. if object_ID('[up_SearchAddressByNameV1]') is not null
  4. Drop Procedure [up_SearchAddressByNameV1]
  5. Go
  6. create proc up_SearchAddressByNameV1
  7. (
  8. @Name nvarchar(200)
  9. )
  10. As
  11. set nocount on
  12. declare @sql nvarchar(max),@contains nvarchar(500)
  13.  
  14. declare @tmp Table (Name nvarchar(50))
  15.  
  16. while patindex('% %',@Name)>0
  17. begin
  18. set @Name=replace(@Name,' ',' ')
  19. end
  20.  
  21. set @sql ='select ''' +replace(@Name,' ',''' union all select ''')+''''
  22. set @contains='"'+replace(@Name,' ','*" Or "')+'*"'
  23.  
  24. insert into @tmp(Name) exec(@sql)
  25.  
  26. if object_id('tempdb..#') is not null drop table #
  27.  
  28. ;with cte_SearchParent as
  29. (
  30. select a.ID,a.Parent,a.LevelNo,convert(nvarchar(2000),a.Name) as AddressPath from TBAddress a where exists(select 1 from TBAddress x where contains(x.Name,@contains) And x.ID=a.ID)
  31. union all
  32. select a.ID,b.Parent,b.LevelNo,convert(nvarchar(2000),b.Name+'/'+a.AddressPath) as AddressPath
  33. from cte_SearchParent a
  34. inner join TBAddress b on b.ID=a.Parent
  35. --and b.LevelNo=a.LevelNo -1
  36. and b.LevelNo>=1
  37. )
  38. select a.ID,a.AddressPath
  39. into #
  40. from cte_SearchParent a
  41. where a.LevelNo=1 and exists(select 1 from @tmp x where a.AddressPath like '%'+x.Name+'%' having count(1)=(select count(1) from @tmp))
  42.  
  43. ;with cte_result as
  44. (
  45. select a.ID,a.LevelNo,b.AddressPath
  46. from TBAddress a
  47. inner join # b on b.ID=a.ID
  48. union all
  49. select b.ID,b.LevelNo,convert(nvarchar(2000),a.AddressPath+'/'+b.Name) As AddressPath
  50. from cte_result a
  51. inner join TBAddress b on b.Parent=a.ID
  52. --and b.LevelNo=a.LevelNo+1
  53.  
  54. )
  55. select distinct a.ID,a.AddressPath
  56. from cte_result a
  57. where not exists(select 1 from TBAddress x where x.Parent=a.ID)
  58. order by a.AddressPath
  59. Go

procedure:up_SearchAddressByNameV1

4.3测试存储过程:

  1. exec up_SearchAddressByNameV1 '广 大'

共返回195行记录。

4.4 客户端统计信息:

平均的执行耗时:  166毫秒

5.测试,方法3

在方法2中,我们在Name列上创建全文索引提高了查询性能,但我们不仅仅局限于一两个方法,下面我们介绍第3个方法。

第3个方法,通过修改表的结构和创建全文索引。在表TBAddress增加多一个字段FullPath存储各个地址到Level 1的全路径,再在FullPath列上创建全文索引,然后直接通过全文索引来搜索FullPath列中包含“广”和“大”的记录。

5.1 新增加字段FullPath,并更新列FullPath数据:

  1. use test;
  2. go
  3. /*alter table */
  4. if not exists ( select 1
  5. from sys.columns a
  6. where a.object_id = object_id('TBAddress')
  7. and a.name = 'Fullpath' )
  8. begin
  9. alter table TBAddress add Fullpath nvarchar(200);
  10. end;
  11. go
  12. create nonclustered index IX_TBAddress_FullPath on dbo.TBAddress(Fullpath) with(fillfactor=80,pad_index=on);
  13. go
  14. /*update TBAddress */
  15. with cte_fullPath
  16. as ( select ID, Parent, LevelNo, convert(nvarchar(500), isnull(Name, '')) as FPath, Fullpath
  17. from dbo.TBAddress
  18. where LevelNo = 1
  19. union all
  20. select A.ID, A.Parent, A.LevelNo, convert(nvarchar(500), B.FPath + '/' + isnull(A.Name, '')) as FPath, A.Fullpath
  21. from TBAddress as A
  22. inner join cte_fullPath as B on A.Parent = B.ID
  23. )
  24. update a
  25. set a.Fullpath = isnull(b.FPath, a.Name)
  26. from dbo.TBAddress a
  27. left join cte_fullPath b on b.ID = a.ID;
  28. go

5.2 在列FullPath添加全文索引:

  1. alter fulltext index on dbo.TBAddress add(Fullpath language 2052)

5.3 存储过程代码:

  1. Use test
  2. Go
  3. if object_ID('[up_SearchAddressByNameV2]') is not null
  4. Drop Procedure [up_SearchAddressByNameV2]
  5. Go
  6. create proc up_SearchAddressByNameV2
  7. (
  8. @name nvarchar(200)
  9. )
  10. As
  11. declare @contains nvarchar(500)
  12. set nocount on
  13. set @contains='"'+replace(@Name,' ','*" And "')+'*"'
  14.  
  15. select id,FullPath As AddressPath from TBAddress a where contains(a.FullPath,@contains) and not exists(select 1 from TBAddress x where x.Parent=a.ID) order by AddressPath
  16.  
  17. Go

procedure:up_SearchAddressByNameV2

5.4 测试存储过程:

  1. exec up_SearchAddressByNameV2 '广 大'

共返回195行记录。

5.5 客户端统计信息:

平均的执行耗时:  20.4毫秒

6.测试,方法4

直接使用Like对列FullPath进行查询。

6.1存储过程代码:

  1. Use test
  2. Go
  3. if object_ID('[up_SearchAddressByNameV3]') is not null
  4. Drop Procedure [up_SearchAddressByNameV3]
  5. Go
  6. create proc up_SearchAddressByNameV3
  7. (
  8. @name nvarchar(200)
  9. )
  10. As
  11. set nocount on
  12. declare @sql nvarchar(max)
  13.  
  14. declare @tmp Table (Name nvarchar(50))
  15.  
  16. set @Name=rtrim(rtrim(@Name))
  17.  
  18. while patindex('% %',@Name)>0
  19. begin
  20. set @Name=replace(@Name,' ',' ')
  21. end
  22.  
  23. set @sql='select id,FullPath As AddressPath
  24. from TBAddress a where not exists(select 1 from TBAddress x where x.Parent=a.ID)
  25. '
  26. set @sql +='And a.FullPath like ''%' +replace(@Name,' ','%'' And a.FullPath Like ''%')+'%'''
  27. exec (@sql)
  28. Go

procedure:up_SearchAddressByNameV3

6.2 测试存储过程:

  1. exec up_SearchAddressByNameV3 '广 大'

共返回195行记录。

6.3 客户端统计信息

平均的执行耗时:  34毫秒

7.小结

这里通过一个简单的表格,对方法1至方法4作比较。

从平均耗时方面分析,一眼就知道方法3比较符合开始的需求(耗时要控制在几十毫秒内)。

当然还有其他的方法,如通过程序实现,把数据一次性加载至内存中,再通过程序写的算法进行搜索,或通过其他工具如Lucene来实现。不管哪一种方法,我们都是选择最优的方法。实际的工作经验告诉我们,在实际应用中,多选择和测试不同的方法来,选择其中一个满足我们环境的,而且是最优的方法。

Normal
0

7.8 磅
0
2

false
false
false

EN-US
ZH-CN
X-NONE

/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;
mso-font-kerning:1.0pt;}
table.MsoTable15Grid4Accent1
{mso-style-name:"网格表 4 - 着色 1";
mso-tstyle-rowband-size:1;
mso-tstyle-colband-size:1;
mso-style-priority:49;
mso-style-unhide:no;
border:solid #95B3D7 1.0pt;
mso-border-themecolor:accent1;
mso-border-themetint:153;
mso-border-alt:solid #95B3D7 .5pt;
mso-border-themecolor:accent1;
mso-border-themetint:153;
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-border-insideh:.5pt solid #95B3D7;
mso-border-insideh-themecolor:accent1;
mso-border-insideh-themetint:153;
mso-border-insidev:.5pt solid #95B3D7;
mso-border-insidev-themecolor:accent1;
mso-border-insidev-themetint:153;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;
mso-font-kerning:1.0pt;}
table.MsoTable15Grid4Accent1FirstRow
{mso-style-name:"网格表 4 - 着色 1";
mso-table-condition:first-row;
mso-style-priority:49;
mso-style-unhide:no;
mso-tstyle-shading:#4F81BD;
mso-tstyle-shading-themecolor:accent1;
mso-tstyle-border-top:.5pt solid #4F81BD;
mso-tstyle-border-top-themecolor:accent1;
mso-tstyle-border-left:.5pt solid #4F81BD;
mso-tstyle-border-left-themecolor:accent1;
mso-tstyle-border-bottom:.5pt solid #4F81BD;
mso-tstyle-border-bottom-themecolor:accent1;
mso-tstyle-border-right:.5pt solid #4F81BD;
mso-tstyle-border-right-themecolor:accent1;
mso-tstyle-border-insideh:cell-none;
mso-tstyle-border-insidev:cell-none;
color:white;
mso-themecolor:background1;
mso-ansi-font-weight:bold;
mso-bidi-font-weight:bold;}
table.MsoTable15Grid4Accent1LastRow
{mso-style-name:"网格表 4 - 着色 1";
mso-table-condition:last-row;
mso-style-priority:49;
mso-style-unhide:no;
mso-tstyle-border-top:1.5pt double #4F81BD;
mso-tstyle-border-top-themecolor:accent1;
mso-ansi-font-weight:bold;
mso-bidi-font-weight:bold;}
table.MsoTable15Grid4Accent1FirstCol
{mso-style-name:"网格表 4 - 着色 1";
mso-table-condition:first-column;
mso-style-priority:49;
mso-style-unhide:no;
mso-ansi-font-weight:bold;
mso-bidi-font-weight:bold;}
table.MsoTable15Grid4Accent1LastCol
{mso-style-name:"网格表 4 - 着色 1";
mso-table-condition:last-column;
mso-style-priority:49;
mso-style-unhide:no;
mso-ansi-font-weight:bold;
mso-bidi-font-weight:bold;}
table.MsoTable15Grid4Accent1OddColumn
{mso-style-name:"网格表 4 - 着色 1";
mso-table-condition:odd-column;
mso-style-priority:49;
mso-style-unhide:no;
mso-tstyle-shading:#DBE5F1;
mso-tstyle-shading-themecolor:accent1;
mso-tstyle-shading-themetint:51;}
table.MsoTable15Grid4Accent1OddRow
{mso-style-name:"网格表 4 - 着色 1";
mso-table-condition:odd-row;
mso-style-priority:49;
mso-style-unhide:no;
mso-tstyle-shading:#DBE5F1;
mso-tstyle-shading-themecolor:accent1;
mso-tstyle-shading-themetint:51;}

SQLServer地址搜索性能优化例子的更多相关文章

  1. sqlserver 构架与性能优化

    太阳底下没有新鲜事 一.sqlserver 构架结构 1.查询优化器三阶段 1).找计划缓存如果找到直接使用 2).简单语句生成0开销的执行计划 3).正式优化 一般情况下优化到开销小于1.0就会停止 ...

  2. Go -- 性能优化

    今日头条使用 Go 语言构建了大规模的微服务架构,本文结合 Go 语言特性着重讲解了并发,超时控制,性能等在构建微服务中的实践. 今日头条当前后端服务超过80%的流量是跑在 Go 构建的服务上.微服务 ...

  3. 03.SQLServer性能优化之---存储优化系列

    汇总篇:http://www.cnblogs.com/dunitian/p/4822808.html#tsql 概  述:http://www.cnblogs.com/dunitian/p/60413 ...

  4. 转载:SqlServer数据库性能优化详解

    本文转载自:http://blog.csdn.net/andylaudotnet/article/details/1763573 性能调节的目的是通过将网络流通.磁盘 I/O 和 CPU 时间减到最小 ...

  5. SqlServer数据库性能优化详解

    数据库性能优化详解 性能调节的目的是通过将网络流通.磁盘 I/O 和 CPU 时间减到最小,使每个查询的响应时间最短并最大限度地提高整个数据库服务器的吞吐量.为达到此目的,需要了解应用程序的需求和数据 ...

  6. 01.SQLServer性能优化之----强大的文件组----分盘存储

    汇总篇:http://www.cnblogs.com/dunitian/p/4822808.html#tsql 文章内容皆自己的理解,如有不足之处欢迎指正~谢谢 前天有学弟问逆天:“逆天,有没有一种方 ...

  7. SQLSERVER SQL性能优化技巧

    这篇文章主要介绍了SQLSERVER SQL性能优化技巧,需要的朋友可以参考下 1.选择最有效率的表名顺序(只在基于规则的优化器中有效)       SQLSERVER的解析器按照从右到左的顺序处理F ...

  8. SQLServer性能优化之---数据库级日记监控

    上节回顾:https://www.cnblogs.com/dotnetcrazy/p/11029323.html 4.6.6.SQLServer监控 脚本示意:https://github.com/l ...

  9. 02.SQLServer性能优化之---牛逼的OSQL----大数据导入

    汇总篇:http://www.cnblogs.com/dunitian/p/4822808.html#tsql 上一篇:01.SQLServer性能优化之----强大的文件组----分盘存储 http ...

随机推荐

  1. 常见CSS与HTML使用误区

       误区一.多div症 <div class="nav"> <ul> <li><a href="/home/"> ...

  2. 8.仿阿里云虚拟云服务器的FTP(包括FTP文件夹大小限制)

    平台之大势何人能挡? 带着你的Net飞奔吧!:http://www.cnblogs.com/dunitian/p/4822808.html#iis 原文:http://dnt.dkill.net/Ar ...

  3. 分布式系列文章——从ACID到CAP/BASE

    事务 事务的定义: 事务(Transaction)是由一系列对系统中数据进行访问与更新的操作所组成的一个程序执行逻辑单元(Unit),狭义上的事务特指数据库事务. 事务的作用: 当多个应用程序并发访问 ...

  4. ComponentPattern (组合模式)

    import java.util.LinkedList; /** * 组合模式 * * @author TMAC-J 主要用于树状结构,用于部分和整体区别无区别的场景 想象一下,假设有一批连锁的理发店 ...

  5. Xamarin Android 应用程序内图标上数字提示

    最近在用 Xamarin 做一个 Android 应用,打开应用时,如果有新消息,需要在应用内的 Toolbar 或者首页的图标上显示数字提示.在这里和大家分享一下实现方法,如果你有更新好的实现方法, ...

  6. join Linq

    List<Publisher> Publishers = new List<Publisher>(); Publisher publish1 = new Publisher() ...

  7. 机器指令翻译成 JavaScript —— No.2 跳转处理

    上一篇,我们发现大多数 6502 指令都可以直接 1:1 翻译成 JS 代码,但除了「跳转指令」. 跳转指令,分无条件跳转.条件跳转.从另一个角度,也可分: 静态跳转:目标地址已知 动态跳转:目标地址 ...

  8. 微软收购Xamarin,你怎么看?

    今天的最大新闻就是微软收购热门初创企业Xamarin,从网上的反馈大部分都是积极的,也有担心微软在把Xamarin移动开发技术整合进VS的同时,还很有可能废掉MONO的GUI客户端能力只保留.net ...

  9. [译]DbContext API中使用SqlQuery和ExecuteSqlCommand获取存储过程的输入输出参数

    水平有限,欢迎指正.原文:http://blogs.msdn.com/b/diego/archive/2012/01/10/how-to-execute-stored-procedures-sqlqu ...

  10. 分享阿里云推荐码 IC1L2A,购买服务器可以直接打9折,另附阿里云服务器部署ASP.NET MVC5关键教程

    阿里云推荐码为:IC1L2A 阿里云还是不错滴. 以windows server 2008 R2为例,介绍如何从全新的服务器部署MVC5 站点. 新购买的阿里云服务器是没有IIS的,要安装IIS: 控 ...