Table Name is Category.
CategoryId ParentId Name
1 NULL StackOverFlow-1
2 1 StackOverFlow-2
3 1 StackOverFlow-3
4 2 StackOverFlow-4
5 4 StackOverFlow-5
The parent of StackOverFlow-5 is StackOverFlow-4.
The parent of StackOverFlow-4 is StackOverFlow-2.
The parent of StackOverFlow-2 is StackOverFlow-1.
I want to make a function like below:
GetAllCategoryIdsUntilBaseParentByCategoryId(int Id)
{
//..
}
I think it should be a recursive function. Isn’t it?
Pseude code:
int x -> Select ParentId From Category Where Id = 5
int y -> Select ParentId From Category Where Id = x
int z -> Select ParentId From Category Where Id = y
This model should go on where ParentId is null..
How can I do it?
With SQL Server 2008 you can do this in a elegant single CTE query:
Simplifying your schema as:
The query will be:
Results:
As you can see the recursion is in the query. This avoid to generate multiple queries and calls to database.