繁体   English   中英

在SQL Server中对可嵌套结构索引进行排序

[英]Sorting Nestable Structure Index in SQL Server

有一张表Article 我想对数据进行排序。

检查记录4.2.1

感谢您的四个建议和帮助。

我想对这些数据进行排序:

ArticleCode        
------------
1
1.1
1.2
1.3
2
3
3.1
3.2
3.3
3.4
3.5
4
4.1
4.1.1
4.1.2
4.1.3
4.2
4.2.1
4.2.2
4.2.3
4.2.4
4.2.5
4.2.6
4.2.7
4.2.8
4.2.9
4.2.10
4.2.11
4.2.12

我的选择查询:

select ArticleCode 
from Article 
order by ArticleCode

查询结果:

1
1.1
1.2
1.3
2
3
3.1
3.2
3.3
3.4
3.5
4
4.1
4.1.1
4.1.2
4.1.3
4.2
4.2.1
4.2.10
4.2.11
4.2.12
4.2.2
4.2.3
4.2.4
4.2.5
4.2.6
4.2.7
4.2.8
4.2.9

这是您可以执行此操作的一种方法。 它将支持合理的深度(892字节),但不是无限的。 同样,在大型数据集上,这将非常慢,但不能确保您可以在此处避免具有数据结构的性能问题。

declare @article table(ArticleCode varchar(10))

insert @article values
('1')
, ('1.1')
, ('1.2')
, ('1.3')
, ('2')
, ('3')
, ('3.1')
, ('3.2')
, ('3.3')
, ('3.4')
, ('3.5')
, ('4')
, ('4.1')
, ('4.1.1')
, ('4.1.2')
, ('4.1.3')
, ('4.2')
, ('4.2.1')
, ('4.2.10')
, ('4.2.11')
, ('4.2.12')
, ('4.2.2')
, ('4.2.3')
, ('4.2.4')
, ('4.2.5')
, ('4.2.6')
, ('4.2.7')
, ('4.2.8')
, ('4.2.9')

select *
from @article
order by convert(hierarchyid, '/' + replace(ArticleCode, '.', '/') + '/') --have to append the / before and after so the values are a valid hierarchyid

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM