Say that have the following CTE that returns the level of some tree data (adjacency model) that I have (taken from Hierarchical data in Linq – options and performance):
WITH hierarchy_cte(id, parent_id, data, lvl) AS
(
SELECT id, parent_id, data, 0 AS lvl
FROM dbo.hierarchical_table
WHERE (parent_id IS NULL)
UNION ALL
SELECT t1.id, t1.parent_id, t1.data, h.lvl + 1 AS lvl
FROM dbo.hierarchical_table AS t1
INNER JOIN hierarchy_cte AS h ON t1.parent_id = h.id
)
SELECT id, parent_id, data, lvl
FROM hierarchy_cte AS result
I was wondering if there would be any performance increase by doing the recursion in C# instead of SQL. Can anyone show me how to perform the same work that the CTE does with a recursive C# function assuming I have a IQueryable where Tree is an entity representing an entry in the hierarchical table? Something along the lines of:
public void RecurseTree(IQueryable<Tree> tree, Guid userId, Guid parentId, int level)
{
...
currentNode.level = x
...
Recurse(tree... ,level + 1)
}
Would be cool to see this is easy to do using a lambda expression.
Recursion in SQL Server is horrendously slow by comparsion but it does work.
I’d have to say that T-SQL is somewhat limited but it was never meant to do all those operations in the first place. I don’t believe there is any way you can make this happen with an IQueryable if you inted to run this against you SQL Server instance but you can do it in memory on the machine running the code using LINQ-to-Objects in a relatively compact manner.
Here’s one way to do that: