I ran into this question looking for information about the hierarchyid
data type, and thought it would be interesting if someone else came after me to see the hierarchyid
insertion code according to the question.
I do not claim that these are the only ways to insert hierarchyid
s, but I hope this helps those who, like me, do not have experience with this data type.
Using this table,
create table OrgChart ( Position hierarchyid, Title nvarchar(50) )
you can use Parse to directly insert hierarchyid
using 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 hierarchyid
GetRoot and GetDescendant data type methods to create a hierarchy. I found this method more cumbersome, but I believe that using these methods is necessary if you programmatically manage 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 the links provided in another answer, but hopefully this code to try also helps.