以递归方式从表中获取数据

时间:2012-08-14 09:42:01

标签: sql stored-procedures sybase

我需要以递归方式从表中获取数据。 数据就像 将有一个父母,其中有多个孩子。 数据的结构就像一棵树,但每个节点都有多个子节点。

表结构如下:

Description----column name
--------------------------
key of the item---key
parent of the item----parent

我可以从另一个表中获取root的密钥,如下所示:

select key from BSC where name="0201".

使用此密钥我需要将所有孩子取出,直到这棵树的叶子。

我唯一的输入是项目的名称。 如果我想要根的孩子我可以使用以下方式获取它:

select bpkey from MYTABLE where parent in (select bpkey from BSC where name="0201")

但这只是root的孩子。我需要带孩子和孩子的孩子......而且还在继续。

但我需要获取该树中的所有密钥。

我在编写SQL查询时并不擅长。 可能我认为我们需要在这里进行递归和存储过程。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

假设您有一个临时表来保存层次结果。

create table #temp2(id int, parentid int null)

插入您希望从中获得层次结果的唯一记录。

declare loop cursor
   for select * from #temp2
go

declare @id int
declare @parentid int

open loop
fetch loop
    into @id, @parentid
while(@@sqlstatus = 0)
begin 

insert into #temp2
select id,parentid from #temp1 where parentid=@id

fetch loop
    into @id, @parentid
end
close loop
DEALLOCATE cursor loop

上述查询还假设源表为#temp1,结果表为#temp2

答案 1 :(得分:0)

如果您的Sybase版本支持公用表表达式(即:sql where)

;with cte as
(
    select [key], parent from yourtable
    union all
    select t1.[key], t2.parent from yourtable t1
    inner join cte t2 on t1.parent=t2.[key]
)
    select * from cte where parent= [parent to search for]
相关问题