[!][!]
兄弟,这是我在SQL SERVER 2000 中测试通过的存储过程:
CREATE PROCEDURE TEST
@ID VARCHAR(20)
AS
BEGIN
DELETE FROM B
--先插入第一层下节点:
INSERT INTO B SELECT ID,1 FROM A WHERE SJID = @ID
--然后用一个循环
WHILE (SELECT COUNT(*) FROM A INNER JOIN B ON A.SJID = B.ID AND FLAG = 1) > 0
BEGIN
INSERT INTO B SELECT A.ID,0 FROM A INNER JOIN B ON A.SJID = B.ID AND FLAG = 1
UPDATE B SET FLAG = 2 WHERE FLAG = 1
UPDATE B SET FLAG = 1 WHERE FLAG = 0
END
END
CREATE Procedure Test1
@ID Varchar(20)
AS
BEGIN
Declare @lev int
Set @lev=1
Select Sjid,ID,@lev as lev into #temp From A where sjid=@id
While Exists(Select * from #temp Where lev=@lev)
Begin
insert into #temp select Sjid,id,@lev+1 from A where Sjid in (select id from #temp where lev=@lev)
Set @lev=@lev+1
End
Select * from #temp order by lev,Sjid,id
END
GO
如果是ORACLE数据库可以直接用查询来实现
Select level <,column_name> from <table_name>
connect by prior <id_name> = <uplevel_id_name>
start with <id_name> = '<value>' order by <id_name>
希望你能看懂。
如果不是ORACLE可以用递归算法来查找