0

Each entity can have one parent. I need to find all the descendants of a given entity.

Is it possible with just SQL?

I can only think in terms of a script, and it won't be as fast as sql alone.

I'm using PHP and MS SQL Server 2005, and doctrine 2 DBAL

D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
HappyDeveloper
  • 12,480
  • 22
  • 82
  • 117
  • Do you mean you wish to find the direct first-generation descendants of each entity, or the entire tree of _n_ generations beneath an entity? – Michael Berkowski Sep 30 '11 at 18:33

2 Answers2

2

For SQL Server 2005+, you can use a recursive CTE.

WITH cteRecursion AS (
    SELECT PrimaryKey, 1 AS Level
        FROM YourTable
        WHERE PrimaryKey = @GivenEntity
    UNION ALL
    SELECT t.PrimaryKey, c.Level+1
        FROM YourTable t
            INNER JOIN cteRecursion c
                ON t.ParentKey = c.PrimaryKey
)
SELECT PrimaryKey, Level
    FROM cteRecursion
    ORDER BY Level, PrimaryKey;
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
  • Wow this is neat, thanks. But I don't understand the @GivenEntity part, what does it mean? Sorry, I'm new to this – HappyDeveloper Sep 30 '11 at 20:01
  • @HappyDeveloper In your question, you said "I need to find all the descendants of a given entity", so `@GivenEntity` is the variable representing the value for the entity whose descendants you wish to find. – Joe Stefanelli Sep 30 '11 at 20:44
1

PHP will run one SQL statement at a time so you will need to create this list in a loop. A good alternative is to use nested sets.

Community
  • 1
  • 1
webbiedave
  • 48,414
  • 8
  • 88
  • 101