数据库服务器SQL2000需求:树状结构数据也就是表中有字段ID、PID其中PID用来关联ID现在我要取随机10条根数据.最后的结果集中要包含这10条数据以及这10条数据所牵涉到的所有的父节点ID...

解决方案 »

  1.   

    http://topic.csdn.net/u/20110513/19/36b54243-4323-4b33-af73-2557782a5a3d.html
    这个帖子不是给出函数了吗?然后嵌套一下select top 10 * from (嵌套结果) aa order by newid() 
      

  2.   

    我的意思是select top 10 ID from xxx
    然后在根据这10条ID 读取这10条的所有节点集合...  在另一个帖子上我也说过了.用程序循环...但是数据库多的时候速度实在不能接受..一个页面打开将近10s
      

  3.   

    需要显示出来...网上找过资料,也曾考虑过用while循环、游标来做..或者升级到2005可能会有更多的方法来支持但是..实在是对SQL不是很精通...
      

  4.   

    -->测试数据
    if object_id('[tb]') is not null drop table [tb]
    go
    create table tb(ID int, PID int)
    insert into tb select 1,0  
    insert into tb select 2,1  
    insert into tb select 3,1  
    insert into tb select 4,2  
    insert into tb select 5,3  
    insert into tb select 6,5  
    insert into tb select 7,6
    go-->函数:寻找某ID的父节点
    CREATE FUNCTION f_Pid(@ID int)
    RETURNS @t_Level TABLE(ID int)
    AS
    BEGIN
     INSERT @t_Level SELECT @ID
     SELECT @ID=PID FROM tb
     WHERE ID=@ID
      AND PID IS NOT NULL
     WHILE @@ROWCOUNT>0
     BEGIN
      INSERT @t_Level SELECT @ID
      SELECT @ID=PID FROM tb
      WHERE ID=@ID
       AND PID IS NOT NULL
     END
     RETURN
    END
    go-->查询
    select top 3 * into #t1 from tb order by newid()
    declare my_cursor cursor  for select id from #t1
    open my_cursor
    declare @id int
    select * into #t2 from tb where 1=2
    fetch next from my_cursor into @id
    while(@@fetch_status=0)
      begin
        insert into #t2
        select t.* from tb t join dbo.f_Pid(@id) b on t.ID=b.id
        where not exists(select 1 from #t2 where id=t.id)
        fetch next from my_cursor into @id
      end
    close my_cursor
    deallocate my_cursor-->随机的3条记录
    select * from  #t1
    /**
    ID          PID
    ----------- -----------
    4           2
    6           5
    7           6(3 行受影响)
    **/-->随机记录所涉及到的父节点
    select * from #t2
    /**
    ID          PID
    ----------- -----------
    1           0
    2           1
    4           2
    3           1
    5           3
    6           5
    7           6(7 行受影响)
    **/drop table #t1,t2