当子 id 包含“."时,sql server 中的分层排序 [英] Hirarchical sorting in sql server when child id contains '.'
本文介绍了当子 id 包含“."时,sql server 中的分层排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些像下面这样的孩子
i have some childid like below
childid
------------
1.1
1.2
2.8
2.7
6.5
6.5.1
6.5.15
7.1
8
排序顺序为
childid
--------
1.1
1.2
2.7
2.8
6.5
6.51
6.5.15
7.1
我尝试转换为如下所示的老虎
i tried to converted to intiger like below
declare @str nvarchar(max)='1.23.2';
set @str=(select replace(@str,'.',''))
select @str
但是当
7.1
8
来了它给出了像
8
7.1
但我需要像下面这样的订单
but i need order like below
7.1
8
如果数字像
7.1.1
7.1.8
6.7.7.7
那么顺序应该是
6.7.7.7
7.1.1
7.1.8
希望有人能帮我解决这个问题
i hope somebody can help me to solve this
推荐答案
试试看:
我也改变了处理像123abc"这样的非数字值的方法.
I changed the approach to deal with non-numeric values like '123abc' too.
declare @ids table(idList varchar(100))
insert into @ids values
('1.1')
,('1.2')
,('2.8')
,('2.7')
,('6.5')
,('6.5.1')
,('6.5.15')
,('7.1')
,('8');
select idList,padded.OrderBy
from @ids as ids
cross apply(select cast('<r>' + replace(idList,'.','</r><r>') + '</r>' as xml)) as AsXml(val)
cross apply
(
select right(' ' + rtrim(x.y.value('.','varchar(max)')),10)
from AsXml.val.nodes('/r') as x(y)
for xml path('')
) as padded(OrderBy)
order by padded.OrderBy
这篇关于当子 id 包含“."时,sql server 中的分层排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文