Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / T-SQL

Use hierarchyid to query Hierarchical data

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
13 Mar 2019MIT3 min read 4.4K   3   1
In this SQL minute we’ll look at how you can use hierarchyid to query hierarchy data.  This is a two-part article.  In this article we look at how to do one query to get portion of the hierarchy.

In this SQL minute we’ll look at how you can use hierarchyid to query hierarchy data.  This is a two-part article.  In this article we look at how to do one query to get portion of the hierarchy.  Next week, we will look to see how to query the entire tree.

If you’re studying for the 70-761 exam, you’ll find there aren’t many intermediate SQL problems with explanation for you to solve.  To help you out I’ve put together my SQL Practice Work book.  When you subscribe to receive it, you’ll not only get my workbook with video answers, but an engaging problem to solve sent to your inbox each week.

For this problem we will use the AdventureWorks database.

Who works for JoLynn?

Hidden in the Employee table is AdventureWorks’ organizational structure. Though the HRIS specialist is adept at basic SELECT and JOINS, she is having a hard time finding out who reports to JoLynn Dobney.

Can you help her by writing some T-SQL to find all of JoLynn’s direct reports? For each direct report, output their JobTitle, First Name, and Last Name.

Write your query, and then look below to see how I did it!

Answer using hierarchyid functions.

Before we get to the answer lets get some terminology under our belt.  Hierarchical data can be though of as a tree.  In the diagram below you’ll see an organization chart.  The tree is upside down, as it “branches” down the page, instead of up to the sky.

Notice that the tree starts with a Root, this is the tree’s beginning.

Image 1

Also, each node in the tree is connected to zero or more other nodes.  Any node can be considered a parent.  Any nodes branching from it are children.

Using the family tree metaphor, the parent has decedents, which are the children.  And the children have ancestors, which are parents and grandparents…

I’m old school, so most of the hierarchical data I’m used to using in a database is in the form of a parentID column being the foreign key to a primary key.

For example, the EmployeeID is the primary key and the Manager ID the parent.

Image 2

In the adventure works database this is done differently.  Here the reporting structure is conveyed using the hierarchyid type.  This type provides a means to relate the parent-child relationships using one field.

HierarchyID Type built-in Functions

A hierarchyid value is a hash value.  Its value is in the built-in function we can use to navigate the hierarchy, such as:

  • GetAncestor – Return the hierarchyid of the parent of the current row.
  • GetDescendant – Return the hierarchyid of a child of the current row.
  • GetRoot – Return the top (root) of the hierarchy.

To solve this problem I’m going to use the GetAncestor function to return the parent hierarchyid.  The idea is to first get the hierarchyid for JoLynn, and then return all records whose ancestor hierarchyid matches hers.

Below is the code I used to write the query. In the first part we get JoLynn’s hierarchyid.

In the second part we get hierarchyid of an employee’s boss. If it matches JoLynn’s hierarchyid, then we keep the row in our result…

SQL
--get direct reports  
--Part 1:  Find JoLynn’s hierarchyID in Employee Database
DECLARE @CurrentEmployee HIERARCHYID;
SELECT @CurrentEmployee=OrganizationNode
FROM   HumanResources.Employee E
       INNER JOIN Person.Person P ON
       E.BusinessEntityID = P.BusinessEntityID
WHERE  P.FirstName ='JoLynn' AND P.LastName ='Dobney';

--Part 2:  Find all direct reports for JoLynn
SELECT E.JobTitle,
       P.FirstName,
       P.LastName
FROM   HumanResources.Employee E
       INNER JOIN Person.Person P ON
       E.BusinessEntityID = P.BusinessEntityID
WHERE  OrganizationNode.GetAncestor(1)= @CurrentEmployee;

Here is another way to write the same code using a subquery!

SQL
SELECT E.JobTitle,
       P.FirstName,
       P.LastName
FROM   HumanResources.Employee E
       INNER JOIN Person.Person P ON
       E.BusinessEntityID = P.BusinessEntityID
WHERE  OrganizationNode.GetAncestor(1)=  
       (SELECT OrganizationNode
        FROM   HumanResources.Employee E
               INNER JOIN Person.Person P ON
               E.BusinessEntityID = P.BusinessEntityID
        WHERE  P.FirstName ='JoLynn' AND P.LastName ='Dobney')

The subquery returns a single value, the same as returned in the first step where we saved it to @currentEmployee.

Let me know if you have another way to solve the problem. Just post it in the comments. Also, if you want to get on my list to get sent a new problem to solve each week, don’t forget to SQL Practice Work book.

The post Use hierarchyid to query Hierarchical data appeared first on Essential SQL.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Easy Computer Academy, LLC
United States United States
Hello my name is Kris. I’m here because I am passionate about helping non-techie people to overcome their fear of learning SQL.

I know what it is like to not know where to start or whether the time spent learning is worth the effort. That is why I am here to help you to:
- Get started in an easy to follow step-by-step manner.
- Use your time wisely so you focus on what is important to learn to get the most value from your time.
- Answer your questions. Really! Just post a comment and I’ll respond. I’m here to help.

It wasn’t long ago that I was helping a colleague with some reporting. She didn’t know where to start and soon got overwhelmed and lost as she didn’t know SQL.

I felt really bad, as she was under pressure to get some summary information to her boss, the built-in reports were falling short, and to make them better would require her to know SQL. At that time that seemed impossible! It in dawned on me, it doesn’t have to be that way.

Then I discovered a way for anyone with the desire to easily learn SQL. I worked with my co-worker, started to teach her what I learned and soon she was able to write reports and answer her boss’ questions without getting stressed or ploughing hours into manipulating data in Excel.

It hasn’t always been easy. Sometimes the information seems abstract or too conceptual. In this case I’ve found out that a visual explanation is best. I really like to use diagrams or videos to explain hard-to-grasp ideas.

Having video, pictures, and text really help to reinforce the point and enable learning.

And now I want to help you get the same results.

The first step is simple, click here http://www.essentialsql.com/get-started-with-sql-server/

Comments and Discussions

 
Bughi Pin
Member 1416536013-Mar-19 19:40
Member 1416536013-Mar-19 19:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.