Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Replace Hierachy text node with IDs

Author  Topic 

Intrepid121
Starting Member

1 Post

Posted - 2011-07-02 : 04:23:39
Hi,

Its been a while since i have done procedural SQL so would appreciate any help you can give to help get me back over the re-learning curve.

I have a table :

CREATE TABLE Hierarchy (
Node varchar(255)NOT NULL ),
ParentNode varchar(255),
Level tinyint,
Lineage varchar(255) )

Which contains data similar to the below to 10 levels

Node Parent Node Level Lineage
UK NULL 1 \UK
England UK 2 \UK\England
Scotland UK 2 \UK\Scotland
Wales UK 2 \UK\Wales
..

What I now need to do is replace the lineage with IDs based on the node and pad 10 chars long:

Node Parent Node Level Lineage
UK NULL 1 \0000000001
England UK 2 \0000000001\0000000002
Scotland UK 2 \ 0000000001\0000000003
Wales UK 2 \ 0000000001\0000000004
....

What would be the best\ quickest way to achieve this?

Thanks

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-07-02 : 09:18:35
Don't know if this is the quickest/best way, but here is one way. I can't help thinking that there is a simpler way. The code below parses, but I have not run it on actual data. So if you choose to use it, run the select statement (as I have it now) to see if Lineage2 is what you are looking for. If that looks correct, uncomment the update statement and remove the select and run to do the update.
with cte1 as
(
select
*,
row_number() over (order by level) RN
from
Hierarchy
),
cte2 as
(
select
*,
cast('\'+ right('000000'+cast(RN as varchar(32)),6) as varchar(max)) as Lineage2
from cte1 where Level = 1
union all
select c1.*,
c2.Lineage2+cast('\'+ right('000000'+cast(c1.RN as varchar(32)),6) as varchar(max))
from
cte2 c2
inner join cte1 c1 on
c2.Node = c1.ParentNode
)
-- update cte2 set Lineage = Lineage2;
select * from cte2;
Go to Top of Page
   

- Advertisement -