关于ASP递归的一个问题。。求解。。谢谢

来源:百度知道 编辑:UC知道 时间:2024/09/25 07:00:25
我的数据结构是这样的。。比如:
ID Parent_id
1 0
2 1
3 2
4 3
5 4
6 4
7 6

我试着用递归算出他们的层数。

function showLayer(id,i)
if id="" then exit function
set rs=conn.execute("select * from [Userinfo] where parent_id="&id)
if not(rs.eof and rs.bof) then
call showLayer(rs("id"),i+1)
else
response.Write i
end if
end function

调用:showLayer(1,0)

这样的话遍历算出来的层数不对。ID为1的下级层应该有 5层才对。。但是只算出来了4层,ID为7的层应该没有算到,不知道为什么。大家有什么好的解决方法 来算出相应的层数?或者有什么好的相关解决办法给我说下。跪求。。~~谢谢大家。。。。
1楼的答案不对。。这样的话会引起错误。因为ID为空。。错误 '80020009' 发生意外。

如果你自己写的能运行,只需将set rs=conn.execute("select * from [Userinfo] where parent_id="&id)
改成set rs=conn.execute("select max(id) as id from [Userinfo] where parent_id="&id)

如果你自己的运行不了,
可以写成这样
<%
function showLayer(id,i)
if id<>"" then
set rs=conn.execute("select max(id) as id from [Userinfo] where parent_id="&id)
if not(rs.eof and rs.bof) then
i=i+1
call showLayer(rs("id"),i)
end if
showlayer=i-1
end if
end function
response.Write(showlayer(1,0))
%>

你用的是where parent_id="&id
第一层,parent_id=1, i=0 (传入参数id=1,i=0)
第二层,parent_id=2, i=1 (传入参数id=2,i=1)
第三层,parent_id=3, i=2 (传入参数id=3,i=2)
第四层,parent_id=4, i=3 (传入参数id=4,i=3)
执行第四层后,parent_id=5,(传入参数id=5,i=4)
因为parent_id=5的记录没有,where parent_id=5的记录找不到,所以只算出来了4层。

改成:
function showLayer(id,i)
if id="" then exit function