views:

441

answers:

2

Using Hierarchy data type on SQL 2008. Nodes in my hierarchy go like this:

value   node 
36    /8/1/
38    /8/2/
34    /8/3/
40    /8/4/
42    /8/5/
44    /8/6/
46    /8/7/
48    /8/8/

I'd like to rearrange nodes so that /8/3/ and /8/1/ switch places. Any idea on how to do this?

Only idea that I have so far is that I load all nodes on a level in Array, order them the way I want them to be, delete them from table and insert in sorted form.

A: 

Found the solution

http://technet.microsoft.com/en-us/library/bb677256.aspx

Vnuk
+3  A: 

If (like in your example) you know the hierarchyid values you want to manipulate in advance, you can do it directly, e.g.:

-- Place 1st node between 2nd and 3rd
UPDATE yourTable SET node = CAST('/8/2.5/' AS hierarchyid) WHERE value = 36;
-- Move 3rd node to 1st
UPDATE yourTable SET node = CAST('/8/1/' AS hierarchyid) WHERE value = 34;

If you need to get your new hierarchyid values dynamically, take a look into the GetDescendant() and GetAncestor() functions. Using that, the example would look something like this:

DECLARE @Parent hierarchyid, @Child1 hierarchyid, @Child2 hierarchyid

-- Grab hierarchyids from 2nd and 3rd node
SELECT @Child1 = node FROM yourTable WHERE value = 38;
SELECT @Child2 = node FROM yourTable WHERE value = 34;
-- Get the parent hierarchyid
SELECT @Parent = @Child1.GetAncestor(1);

-- Update 1st node to end up between 2nd and 3rd
UPDATE yourTable SET node = @Parent.GetDescendant(@Child1, @Child2) WHERE value = 36;
-- Update 3rd node to end up before 2nd
UPDATE yourTable SET node = @Parent.GetDescendant(NULL, @Child1) WHERE value = 34;

Note that the hierarchyids do not stay the same in this example. At least one will end up using a 'fraction' for its position (e.g. '/8/2.5/' instead of '/8/3/').

Henrik Opel
Oups, a minute to late...
Henrik Opel
I didn't know that you could update the hierarchyid like so. That is the answer to my problem. I cannot undo my accepted answer right now, but I will accept yours. Thanks
Vnuk