日期:2014-05-18  浏览次数:20455 次

求一遍历树的存储过程
知道某一节点ID,现在要列出它所在的那个分支的所有父节点
在程序中控制要多次访问数据库,现在想用存储过程实现!
表如下:编号,父类编号,名称
uid, parent_id, name

------解决方案--------------------
SQL code
CREATE PROCEDURE usp_GetAllParentNodesByUid
(
@uid INT
)
AS
BEGIN
    DECLARE @tempId INT
    SET @tempId=@uid
    CREATE TABLE #([uid] INT,[parent_id] INT,[name] NVARCHAR(10))
    WHILE @tempId IS NOT NULL
    BEGIN
        INSERT INTO # SELECT * FROM [yourTable] WHERE [uid]=@tempId
        SELECT @tempId=[parent-Id] FROM [yourTable] WHERE [uid=@tempId]
    END
    SELECT * from #
    DROP TABLE #
END

------解决方案--------------------
CREATE PROCEDURE usp_GetAllParentNodesByUid
(
@uid INT
)
AS
BEGIN
DECLARE @tempId INT
SET @tempId=@uid
CREATE TABLE #([uid] INT,[parent_id] INT,[name] NVARCHAR(10))
WHILE @tempId IS NOT NULL
BEGIN
INSERT INTO # SELECT * FROM [yourTable] WHERE [uid]=@tempId
SELECT @tempId=[parent-Id] FROM [yourTable] WHERE [uid=@tempId]
END
SELECT * from #
DROP TABLE #
END

------解决方案--------------------
关注
------解决方案--------------------
CREATE PROCEDURE dbo.GetParentId
(
@id int
)
AS
create table #temp(id int, parentid int)
insert into #temp select uid ,ParentId from table where uid=@Id
while @@rowcount>0
begin
insert #temp select a.uid,a.Parent_id from table a,#temp b where a.uid = b.parentid 
if(exists (select 1 from #temp where parentid =0))
break
end
select top 1 * id from #temp
RETURN 
没调试,说下思路
------解决方案--------------------
学习下,知道的,大家来说说这思路