一个存储过程[返回一棵树]

此过程是根据一个id,返回此id的数据及其子类数据

例如返回树型层次结构的数据

CREATE PROCEDURE? sp_GetTree (
?@ID int)
AS
--如果存储过程中包含的一些语句并不返回许多实际的数据,则该设置由于大量减少了网络流量,因此可显著提高性能。
set nocount on
--
declare @tmp table (ID int,Title varchar(100),ParentID int)
--将自身插入临时表
insert @tmp select ID,Title,ParentId from Pub_Information where ID=@ID
--递归查询是否有符合条件的子类记录
while exists
(select 1
?from Pub_Information a,@tmp b
?where a.ParentID=b.ID and a.ID not in (select ID from @tmp))
--将符合条件的记录插入临时表
insert @tmp
select a.ID,a.Title,a.ParentID
from? Pub_Information a,@tmp b
where a.ParentID=b.ID and a.ID not in (select ID from @tmp)
--获取临时表中的结果
select * from @tmp
--返回数据
set nocount off


GO

posted @ 2005-08-15 02:45  meteorcui  阅读(199)  评论(0编辑  收藏  举报