日期:2014-05-19  浏览次数:20544 次

请用“存储过程”实现对树的查询,谢谢。
我有一个用来实现树形的表,其结构如下:ID,ParentID,Text,ID是唯一的。

现在要求用“存储过程”(函数我已经看过了,现在需要用存储过程实现)来实现对树的查询,即输入任意一个ID,将其所有上一级所有结点都查询出来,谢谢了。

------解决方案--------------------
--查詢結果中包含當前節點

--建立測試環境
Create Table TEST
(ID Int,
ParentID Int,
[Text] Varchar(10))
Insert TEST Select 1, 0, 'A1 '
Union All Select 2, 1, 'A2 '
Union All Select 3, 1, 'A3 '
Union All Select 4, 2, 'A4 '
Union All Select 5, 3, 'A5 '
Union All Select 6, 5, 'A6 '
GO
--建立存儲過程
Create ProceDure SP_GetParent(@ID Int)
As
Begin
Select * Into #T From TEST Where ID = @ID
While @@ROWCOUNT > 0
Insert #T Select A.* From TEST A Inner Join #T B On A.ID = B.ParentID And A.ID Not In (Select ID From #T)
Select * From #T Order By ID
Drop Table #T
End
GO
--測試
EXEC SP_GetParent 5
EXEC SP_GetParent 6
GO
--刪除測試環境
Drop Table TEST
Drop ProceDure SP_GetParent
--結果
/*
ID ParentID Text
1 0 A1
3 1 A3
5 3 A5

ID ParentID Text
1 0 A1
3 1 A3
5 3 A5
6 5 A6
*/