I am interested in writing an IQueryable interface extension method. The method will return all recursive data of the specified selector.
public static class MyExtensions
{
public static IQueryable<IRecursion<T>> SelectRecursive<T>(this IQueryable<T> source, Func<T, IQueryable<T>> selector)
{
}
public interface IRecursion<T>
{
int Depth { get; }
T Item { get; }
}
}
Usage example:
var allChildren = tblCompanies
.Where(c => c.pkCompanyID == 38)
.SelectRecursive(p => tblCompanies.Where (c => c.pkCompanyID == p.fkCompToCompID));
The SQL code generated by the function will be something like this.
WITH CompanyCTE(ID, parentID, depth) AS
(
SELECT
pkCompanyID,
fkCompToCompID,
0
FROM
tblCompany
UNION ALL
SELECT
tblCompany.pkCompanyID,
tblCompany.fkCompToCompID,
CompanyCTE.depth + 1
FROM
tblCompany
JOIN CompanyCTE ON tblCompany.fkCompToCompID = CompanyCTE.ID
)
SELECT
tblCompany.*,
CompanyCTE.depth
FROM
CompanyCTE
JOIN tblCompany ON CompanyCTE.ID = tblCompany.pkCompanyID
WHERE
parentID = 38
Can this be done? If this is not possible with CTE, perhaps with a SQL 2008 hierarchy?
source
share