1

I'm trying to write an efficient recursive query. I've run across CTEs and have found a number of examples. However, every example I've found is returning the same data that is recursive where I need to return some different data.

For example, my hierarchical data is a table of Locations.

[Locations]
ID int
Title nvarchar(100)
ParentLocationID int

But the data I want to return is in a table of Activities. I want to return all activities associated with a particular location, and all "child" locations.

[Activities]
ID int
Title nvarchar(100)
LocationID int

I'm new to CTEs and can't quite see how to do this from the examples I have. Any help would be appreciated.

1 Answer 1

4

Use the recursive CTE to find all locations in the hierarchy then join the Activities table onto the result of that.

;WITH R
     AS (SELECT ID,
                Title,
                ParentLocationID
         FROM   [Locations]
         WHERE  ID = @LocationId
         UNION ALL
         SELECT L.ID,
                L.Title,
                L.ParentLocationID
         FROM   [Locations] L
                JOIN R
                  ON L.ParentLocationID = R.ID)
SELECT * /*TODO: Select columns of interest*/
FROM   R
       JOIN [Activities] A
         ON A.LocationID = R.ID  
Sign up to request clarification or add additional context in comments.

1 Comment

I see now. You are just doing what the examples I've seen were doing, and then selecting related rows by doing a join on the results. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.