2

テーブルから再帰的にデータをフェッチする必要があります。データは、親があり、その中にいくつかの子が含まれているようなものです。データの構造はツリーに似ていますが、各ノードには複数の子があります。

テーブル構造は次のようになります。

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

以下のように、別のテーブルからルートのキーを取得できます。

select key from BSC where name="0201".

このキーを使用して、このツリーの葉まですべての子をフェッチする必要があります。

私が持っている唯一の入力はアイテムの名前です。ルートの子が必要な場合は、次を使用して取得できます。

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

しかし、これはルートの子にすぎません。子と子の子を取得する必要があります...そして、それは続きます。

しかし、そのツリーのすべてのキーを取得する必要があります。

私はSQLクエリを書くのが得意ではありません。おそらく、ここで再帰とストアド プロシージャを使用する必要があると思います。

誰か助けてくれませんか?

4

2 に答える 2

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

于 2012-08-14T10:15:22.857 に答える
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]
于 2012-08-14T10:42:17.620 に答える