Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Using GetAncestor() in a join

, 26 May 2010
Rate this:
Please Sign up or sign in to vote.
GetAncestor() requires a slightly unusual outlook to get the required results

Scenario

I have a table using a heirarchyID to define a hierarchy of products.
 
I now want to get all lowest level(5) nodes where the 3rd level(2) up has a specific attribute (ElementID = 8). I want to do this using a join!
 

Table Definition

CREATE TABLE [ProductNodes](
    [NodeID] [int] IDENTITY(1,1) NOT NULL,
    [NodeKey] [hierarchyid] NULL,
    [ElementID] [int] NULL,
    [ProductID] [int] NULL
) ON [PRIMARY]
 
First I get the nodes where my attribute matches the required value (ElementID = 8).
SELECT *
FROM ProductNodes PN
WHERE PN.ElementID = 8
 
Now to add the join that will get me the level 5 records. I want all the records which have PN nodekey as the parent 3 levels up.
SELECT PN2.ProductID
FROM ProductNodes PN
  INNER JOIN ProductNodes PN2 ON PN2.NodeKey.GetAncestor(3) = PN.NodeKey
WHERE PN.ElementID = 8
 
The actual data I want is from the secondary table (PN2) rather than selected table.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mycroft Holmes
Software Developer (Senior) Contractor
Singapore Singapore
Started my programming life writing Excel 1.0 macros, God what a long time ago.
 
Now I'm a dotnet developer, I get to influence direction, play with new toys, build stuff, life is wonderful.
 
Greatest buzz you can get, walk past a row of desks and see your application running on all of them (and getting paid).
 
Greatest irritant, pouring 12 months of knowledge and experience into an empty head only to have it leave.

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 26 May 2010
Article Copyright 2010 by Mycroft Holmes
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid