数据库结构:ID、name、sex、fatherID……
存储记录:
1  张三   男  0
2  李四   男  0
3  张三子 男  1
4  张三女 女  1
5  李四子 男  2
6  张三孙 男  3
现在想转换成这种格式,
1  张三   男  0
3  张三子 男  1
6  张三孙 男  3
4  张三女 女  1
2  李四   男  0
5  李四子 男  2用存储过程怎么实现?需要对原有库结构进行调整吗?

解决方案 »

  1.   

    你应该通过这个字段实现呵呵 
    fatherID父子关系字段实现  用个循环吧 2005 可以用 cte
      

  2.   

    select * from 表 order by name,fatherID asc
      

  3.   

    create function dbo.getp(@id int)
    returns varchar(8000)
    as
    begin
     declare @s varchar(8000)
     set @s = right(rtrim(10000+@id),4)
     while exists(select 1 from tb where fatherid = @id)
     select @s = @s+right(rtrim(10000+fatherid),4),@id = fatherid
     return @s
    end
    go
    select * from tb order by dbo.getp(id)