2012-12-16 13 views
0

表名是类别。我如何才能获得所有的categoryIds,直到基础父级?

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) 
{ 
    //.. 
} 

我认为这应该是一个递归函数。不是吗?

Pseude代码:

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 

这种模式应该去where ParentId is null ..

我该怎么办呢?

回答

0

有了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; 

Results

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

正如你所看到的递归是在查询中。这避免了生成多个查询和调用数据库。

相关问题