表名为类别。
CategoryId ParentId Name
1 NULL StackOverFlow-1
2 1 StackOverFlow-2
3 1 StackOverFlow-3
4 2 StackOverFlow-4
5 4 StackOverFlow-5StackOverFlow-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这个模型应该放在where ParentId is null上..
我该怎么做呢?
发布于 2012-12-16 16:30:23
使用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 |正如您所看到的,递归在查询中。这避免了生成对数据库的多个查询和调用。
https://stackoverflow.com/questions/13899532
复制相似问题