这是一个典型的递归问题,参考FAQ中以下三个帖子:http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=92690http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=47256http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=70519

解决方案 »

  1.   

    --示例--测试数据
    create table infotype(id int,parentid int,content varchar(10))
    insert infotype select 30,1 ,'name1'
    union  all      select 31,30,'name2'
    union  all      select 32,31,'name3'
    union  all      select 33,32,'name4'
    union  all      select 34,2 ,'name5'create table info(id int,subject varchar(10),infotype int)
    insert info select 1,'subject1',33
    union  all  select 2,'subject2',32
    union  all  select 3,'subject3',34
    union  all  select 4,'subject4',34
    go--查询指定id的所有子
    create function f_cid(
    @id int
    )returns @re table([id] int,[level] int)
    as
    begin
    declare @l int
    set @l=0
    insert @re select @id,@l
    while @@rowcount>0
    begin
    set @l=@l+1
    insert @re select a.[id],@l
    from [infotype] a,@re b
    where a.[parentid]=b.[id] and b.[level]=@l-1
    end
    return
    end
    go--调用实现查询
    select a.*,b.*
    from infotype a,info b,f_cid(1) c  --查1类下的所有信息
    where a.id=b.infotype and b.infotype=c.id
    go--删除测试
    drop table infotype,info
    drop function f_cid/*--测试结果id          parentid    content    id          subject    infotype    
    ----------- ----------- ---------- ----------- ---------- ----------- 
    32          31          name3      2           subject2   32
    33          32          name4      1           subject1   33(所影响的行数为 2 行)
    --*/
      

  2.   

    类别朋2000多个肯定不会有问题,即使一个最多有一个下级的情况,我测试过1万多条记录的情况,也才6秒多,而且我的电脑配置才256M内存,CII900的CPU
      

  3.   

    是我自己搞错了。zjcxc(邹建)真是高手呀!
      

  4.   

    当表infotype(类别表)多了几个相同的值时,怎么办呢,好象不能执行成功呀