C# 如何获取所有CategoryId直到基本父级?

C# 如何获取所有CategoryId直到基本父级?,c#,sql,sql-server-2008,c#-4.0,C#,Sql,Sql Server 2008,C# 4.0,表名是类别 CategoryId ParentId Name 1 NULL StackOverFlow-1 2 1 StackOverFlow-2 3 1 StackOverFlow-3 4 2 StackOverFlow-4 5

表名是类别

CategoryId      ParentId        Name
1               NULL            StackOverFlow-1
2               1               StackOverFlow-2
3               1               StackOverFlow-3
4               2               StackOverFlow-4  
5               4               StackOverFlow-5
StackOverFlow-5的父级是StackOverFlow-4

StackOverFlow-4的父级是StackOverFlow-2

StackOverFlow-2的父级是StackOverFlow-1

我想做一个如下的函数:

GetAllCategoryIdsUntilBaseParentByCategoryId(int Id)
{
    //..
}
我认为它应该是一个递归函数。不是吗

伪码:

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
当ParentId为null时,此模型应继续运行


如何执行此操作?

使用SQL Server 2008,您可以在一个优雅的CTE查询中执行此操作:

将模式简化为:

create table t (id int, parent_id int, c char(1));

insert into t values 
( 1, Null, 'A'),
  ( 2, 1, 'B'),
  ( 3, 1, 'C'),
     (4, 3, 'D' ),
  ( 5, 1, 'E' );
查询将是:

;with cte as (
  select *, id as node 
  from t 
  union all
  select t.*, cte.node
  from t inner join cte 
     on t.id = cte.parent_id
)
select * 
from cte
where node = 4;
:

正如您所看到的,递归在查询中。这样可以避免生成多个查询和对数据库的调用

| ID | PARENT_ID | C | NODE |
-----------------------------
|  1 |    (null) | A |    4 |
|  3 |         1 | C |    4 |
|  4 |         3 | D |    4 |