Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hierarchyid to a string whose lexical order is the same as the hierarchyid depth-first order

I'm wondering if there's a reasonable, performant way to convert a hierarchyid value to a string whose lexical ordering maintains its natural depth-first ordering.

Thanks!

like image 761
w.brian Avatar asked Aug 27 '12 01:08

w.brian


1 Answers

As per the code below (run it on AdventureWorks2008), you can convert to a varbinary and then nvarchar, using style 1. Without style 1, it doesn't order it correctly.

select convert(nvarchar(20),convert(varbinary(20),OrganizationNode,1),1)
        as OrderableString,
       OrganizationNode.ToString() as ReadableString,
       convert(nvarchar(20),OrganizationNode) as ReadableString2
from humanresources.employee
order by strNode;

Some of the ordering from this gives:

OrderableString     ReadableString  ReadableString2
0x7AD744    /3/1/1/8/   /3/1/1/8/
0x7AD74C    /3/1/1/9/   /3/1/1/9/
0x7AD754    /3/1/1/10/  /3/1/1/10/
0x7AD75C    /3/1/1/11/  /3/1/1/11/
0x7AD764    /3/1/1/12/  /3/1/1/12/
0x7ADA      /3/1/2/     /3/1/2/
0x7ADAB0    /3/1/2/1/   /3/1/2/1/
0x7ADAD0    /3/1/2/2/   /3/1/2/2/
like image 72
Rob Farley Avatar answered Oct 21 '22 08:10

Rob Farley