I have a table like this:
Item { int ItemID int ParentID string Name }
An element is actually a subset of the larger table. An object:
Object { int ObjectID string Color }
So ItemID is FK before ObjectID . Within an Item , a ParentID may refer to another element or to a parent.
What I would like to do is be able to iterate over everything that happens through my parents from the sheet in the Item relationship, until I finally can determine from which ObjectID given list of items is dropped.
I would like to do this in SQL. I am using SQL Server 2008.
That's what I think. I can just ParentID over the ParentID element until I can no longer join the ParentID with another element. This ParentID is the ObjectID I want to return.
I tried to get this to work using internal joins but no luck. I use C #, so if this can be done in linq and I don't suspect that this is possible without being terribly inefficient, that would be fine too.
Answer I went with:
WITH ObjectH (ParentID, ItemID, Level) AS ( -- Base case SELECT ParentID, ItemID, 1 as Level FROM Item WHERE ItemID = @param UNION ALL -- Recursive step SELECT i.ParentID, i.ItemID, oh.Level + 1 AS Level FROM Item i INNER JOIN ObjectH oh ON c.ItemID = oh.ParentID ) SELECT TOP 1 ParentID FROM ObjectH ORDER BY Level DESC
It works.
source share