Hi Friends,
Today we will see how we can search ancestors and descendants in a Index on HierarchyID column. In the previous blog you saw that how can we handle hierarchical data with HierarchyID data type. There we saw creation of table using HierarchyID data type as well as inserting the hierarchical data inside that column. You can go for previous blog;
Now run that select command to see what data is inside the table xthid.
select id.ToString() as id,name from xthid
You can also see this as Tree structure shown below:
Now suppose if you want to select descendant of SQLServer node then you can use IsDescendantOf () method as shown below:
USE HierarchyTest go --Descendant Search Declare @param varchar(20) Declare @temp1 as HierarchyID set @param='SQLServer' –For Which you wants to do descendant search select @temp1=id from xthid where name=@param select id.ToString() as id, name from xthid where id.IsDescendantOf(@temp1)=1 go
Now if you want to do search for ancestors then you can also use IsDescendantOf () method but in a different way shown below:
USE HierarchyTest go --Descendant Search Declare @param varchar(20) Declare @temp1 as HierarchyID set @param='SQLServer' –For Which you wants to do descendant search select @temp1=id from xthid where name=@param select id.ToString() as id, name from xthid where id.IsDescendantOf(@temp1)=1 go
Now if you want to do search for ancestors then you can also use IsDescendantOf () method but in a different way shown below:
USE HierarchyTest go --Ancestor Search Declare @param varchar(20) Declare @temp1 as HierarchyID set @param='MSOffice2010' select @temp1=id from xthid where name=@param select id.ToString() as id, name from xthid where @temp1.IsDescendantOf(id)=1 go
Regards
Prince Rastogi
Like us on FaceBook | Follow us on Twitter | Join the fastest growing SQL Server group on FaceBook
Follow me on Twitter | Follow me on FaceBook