Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some questions about HierarchyId (SQL Server 2008)

I am a newbie in SQL Server 2008 and just got introduced to HierarchyId's.

I am learning from SQL Server 2008 - HIERARCHYID - PART I. So basically I am following the article line by line and while practicing in SSMS I found that for every ChildId some hexadecimal values are generated like 0x,0x58,0x5AC0 etc.

My questions are

  1. What are these hexadecimal values?
  2. Why are these generated and what is their use? I mean where can I use those hexa values?
  3. Do we have any control over those hexa values? I mean can we update etc.
  4. How to determine the hierarchy by looking into those hexa values.. I mean how can I determine which is the parent and which is the child?
like image 760
deeps_rule Avatar asked Dec 16 '09 12:12

deeps_rule


People also ask

What is SQL Server HierarchyID?

The hierarchyid data type is a variable length, system data type. Use hierarchyid to represent position in a hierarchy. A column of type hierarchyid does not automatically represent a tree.

What are the new features in SQL Server 2008?

New HierarchyID datatype SQL server 2008 provides new HierarchyID data type that allows database developers to construct relationships among data elements (columns) within a table. HierarchyID data type has a set of methods that provide tree like functionality.

How do I create a parent child hierarchy in SQL Server?

For SQL to do anything with it, a parent-child tree structure has to be stored in a relational database. These structures are usually stored in one table with two ID columns, of which one references a parent object ID. That lets us determine the hierarchy between data.


1 Answers

Those hex values are simply a binary representation of the hierarchy level. In general, you should not use them directly.

You may want to check out the following example, which I think should be self-explanatory. I hope it will get you going in the right direction.

Create a table with a hierarchyid field:

CREATE TABLE groups (
    group_name       nvarchar(100)  NOT NULL,
    group_hierarchy  hierarchyid    NOT NULL
);

Insert some values:

INSERT INTO groups (group_name, group_hierarchy)
VALUES
    ('root',     hierarchyid::Parse('/')),
    ('domain-a', hierarchyid::Parse('/1/')),
    ('domain-b', hierarchyid::Parse('/2/')),
    ('sub-a-1',  hierarchyid::Parse('/1/1/')),
    ('sub-a-2',  hierarchyid::Parse('/1/2/'));

Query the table:

SELECT 
    group_name,
    group_hierarchy.ToString()
FROM
    groups
WHERE
    (group_hierarchy.IsDescendantOf(hierarchyid::Parse('/1/')) = 1);
like image 67
Daniel Vassallo Avatar answered Oct 13 '22 15:10

Daniel Vassallo