1

我在 SQL Server 2008 的表上定义了一个 hierarchyid 列

假设在第一行,hierarchyid 是 '/1/7/1/'

假设在第二行,hierarchyid 是 '/1/10/1/'

如果 I sort by hierarchyid ASC,那么我将看到第二行,然后是第一行。(排序将按String排序,并且'10'<'7')

但是我(出于与不同系统的兼容性原因)希望先查看第一行,然后查看第二行(即按 int 排序,并且 7<10)

我已经解决了这个问题,通过定义第二个 hierarchyid 列,然后将其设置为与第一个 hierarchyid 列相同,但用点替换所有内部斜线,然后按此排序。

我只是想知道是否有更优雅的方式。

4

2 回答 2

1

我知道这是一个相当古老的问题,但它是谷歌的第一个结果,所以我想我会添加一个实际的答案,以防其他人遇到这个问题。如果没有看到正在使用的 SQL,很难做到 100%,但我怀疑 OP 将层次结构 ID 作为字符串返回并对其进行排序,而不是对层次结构 id 本身进行排序:

例如..

declare @results table (Id int, Hierarchy hierarchyId)

-- :
-- Add your data here
-- :

-- This will not work as it's ordering a string
select Id, Hierarchy.ToString() as SortOrder from @results order by SortOrder

-- This will work as it's ordering the hierarchy id
select Id, Hierarchy.ToString() as SortOrder from @results order by Hierarchy
于 2013-10-07T10:40:13.347 回答
0

您需要隔离两个“/”之间的内容并按其排序。你可以使用这个功能:http ://www.sqlusa.com/bestpractices2005/nthindex/

获取字符串上的第 n 个索引,所以

declare @aux_str varchar(50)
set @aux_str='/1/7/3/'

select dbo.fnNthIndex(@aux_str,'/',2) 

返回 3。您必须找出第三个“/”的位置并获取它之间的内容。

不难,但工作量很大

于 2012-04-17T13:06:52.980 回答