I would like to insert the hierarchyId like this
/
- CEO (Root)
/1/
- Purchase Manager
/1/1/
- Purchase Executive/2/
- Sales Manager
/2/1/
- Sales ExecutiveThis is what the hierarchy i would like to use, is it right one, if so how can i do this, can any one give me some code snippet.
Applies to: SQL Server (all supported versions) Azure SQL Database Azure SQL Managed Instance. 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.
Use hierarchyid as a data type to create tables with a hierarchical structure, or to describe the hierarchical structure of data that is stored in another location. Use the hierarchyid functions in Transact-SQL to query and manage hierarchical data.
I came across this question while searching for information on the hierarchyid
data type, and thought it would be interesting for anyone else coming after me to also see code to insert hierarchyid
s as per the question.
I do not claim that these are the only ways to insert hierarchyid
s, but hopefully it will help those who, like me, have no previous experience working with this data type.
Using this table,
create table OrgChart
(
Position hierarchyid,
Title nvarchar(50)
)
you can use Parse to directly insert the hierarchyid
s using the string paths:
insert into OrgChart(Position, Title)
values (hierarchyid::Parse('/'), 'CEO'),
(hierarchyid::Parse('/1/'), 'Purchase Manager'),
(hierarchyid::Parse('/1/1/'), 'Purchase Executive'),
(hierarchyid::Parse('/2/'), 'Sales Manager'),
(hierarchyid::Parse('/2/1/'), 'Sales Executive')
and use the following query to check the table
select Position.ToString(), * from OrgChart
You can also use the hierarchyid
data type methods GetRoot and GetDescendant to build the hierarchy. I found this method to be more cumbersome, but I suppose using these methods is necessary if you are programmatically managing the hierarchy.
declare @root hierarchyid,
@id hierarchyid
set @root = hierarchyid::GetRoot()
insert into OrgChart(Position, Title) values (@root, 'CEO')
set @id = @root.GetDescendant(null, null)
insert into OrgChart(Position, Title) values (@id, 'Purchase Manager')
set @id = @root.GetDescendant(@id, null)
insert into OrgChart(Position, Title) values (@id, 'Sales Manager')
select @id = Position.GetDescendant(null, null) from OrgChart where Title = 'Purchase Manager'
insert into OrgChart(Position, Title) values (@id, 'Purchase Executive')
select @id = Position.GetDescendant(null, null) from OrgChart where Title = 'Sales Manager'
insert into OrgChart(Position, Title) values (@id, 'Sales Executive')
Definitely check out the links provided in the other answer, but hopefully having this code to try out will help as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With