DECLARE @Manager hierarchyid DECLARE @Sibling hierarchyid
SELECT @Manager = NodeID FROM Employee WHERE EmployeeID = 3
SELECT @Sibling = NodeID FROM Employee WHERE EmployeeID = 2 -- This variable represents Amar
INSERT INTO Employee VALUES(@Manager.GetDescendant(@Sibling, NULL), 1, 'Ajit')
The parameters to GetDescendant are the two nodes between which we want to insert the new node. Let us now check the table data.
SELECT * FROM Employee
The hexadecimal output is unhelpful. Let me add a function to the query. SELECT NodeID, NodeID.GetLevel() AS NodeLevel, EmployeeID, EmployeeName FROM Employee
The GetLevel() function as you would have guessed, returns the level of the node. Let us add nodes at the next level.
Inserting the Second Level To insert the second level of hierarchy write the following lines of code:
DECLARE @Manager hierarchyid DECLARE @Sibling hierarchyid SELECT @Manager = NodeID FROM Employee WHERE EmployeeID = 1 -- This variable represents Ajit
INSERT INTO Employee VALUES(@Manager. GetDescendant(NULL,NULL), 4, 'Abhijit')
Let us add Anand next. DECLARE @Manager hierarchyid DECLARE @Sibling hierarchyid
SELECT @Manager = NodeID FROM Employee WHERE EmployeeID = 1 -- This variable represents Ajit
SELECT @Sibling = NodeID FROM Employee WHERE EmployeeID = 4 -- This variable represents Abhijit
INSERT INTO Employee VALUES(@Manager.GetDescendant(@Sibling, NULL), 5, 'Anand')
Let us now query and check if the levels are as we desire.
SELECT NodeID, NodeID.GetLevel() AS NodeLevel, EmployeeID, EmployeeName FROM Employee
Let me introduce another useful function with hierarchies.
SELECT NodeID, NodeID.GetLevel() AS NodeLevel, NodeID.ToString() AS NodeLocation, EmployeeID, EmployeeName FROM Employee ORDER BY NodeLocation ASC
If you have some experience with the Windows folder hierarchy, it would be easy for you to understand the output of the ToString() function as applied to the hierarchyid data type. I leave adding the last level to you as an exercise.
Conclusion Hierarchies can get much more complex than what has been demonstrated. I would encourage you to refer to online books for a thorough understanding on the usage of hierarchies. You would also need to learn when to use this new approach as opposed to storing hierarchies in XML and in self-referencing tables.
Amaresh Patnaik
Get most out of your technology infrastructure investments with Dell
About CIOL | Media Kit | Site Map | Contact Us | Help | Write to us | Jobs@CyberMedia | Privacy Policy
Copyright © CyberMedia India Online Ltd. All rights reserved. Usage of content from web site is subject to Terms and Conditions.