I have a table like this:
Item
{
int ItemID
int ParentID
string Name
}
Item is actually a subset of a larger table Object:
Object
{
int ObjectID
string Color
}
So ItemID
is an FK to ObjectID
. Within Item
, ParentID
can either refer to another Item or to the parent Object.
What I'd like to do is be able to iterate from a leaf in the Item relationship all the way up through its parents until I finally can determine what ObjectID
a given Item leaf descends from.
I'd like to do this in SQL. I'm using SQL Server 2008.
Here's what I'm thinking. I can just iterate up through the the Item ParentID
until I can no longer join ParentID
with another Item. This ParentID
is the ObjectID
I want to return.
I've been trying to get this to work using inner joins, but no luck. I'm using C# so if this can be done in linq, which i don't suspect it can without being horribly 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
This works.