关于树的排序,大家快来看啊

chenyongxm 2006-06-28 07:55:41
fid fparentid
1 0
2 0
3 1
4 2
5 3
要怎么样才能弄成这样子呢,将子排在父的后面,这只是示例数据,可能有很多级,请不要用什么case来做了,谢谢
1 0
3 1
2 0
4 2
3 1
5 3
...全文
244 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
turenjie 2006-06-29
  • 打赏
  • 举报
回复
收藏学习..............
shingkong 2006-06-28
  • 打赏
  • 举报
回复
学习了。。
新鲜鱼排 2006-06-28
  • 打赏
  • 举报
回复
:)
zjcxc 2006-06-28
  • 打赏
  • 举报
回复
-- 写一个生成 path 的函数就行了

-- 示例数据
CREATE TABLE tb(fid int, fparentid int)
INSERT tb SELECT 1, 0
UNION ALL SELECT 2, 0
UNION ALL SELECT 3, 1
UNION ALL SELECT 4, 2
UNION ALL SELECT 5, 3
GO

-- 生成 path 的函数
CREATE FUNCTION dbo.f_path(
@fid int
) RETURNS varchar(8000)
AS
BEGIN
DECLARE @re varchar(8000)
SELECT @re = RIGHT(10000 + fid, 4), @fid = fparentid
FROM tb
WHERE fid = @fid
WHILE @@ROWCOUNT > 0
SELECT @re = RIGHT(10000 + fid, 4) + @re, @fid = fparentid
FROM tb
WHERE fid = @fid
RETURN(@re)
END
GO

-- 调用函数实现排序
SELECT * FROM tb
ORDER BY dbo.f_path(fid)
GO

-- 删除测试
DROP TABLE tb
DROP FUNCTION dbo.f_path

/*--测试结果
fid fparentid
----------- -----------
1 0
3 1
5 3
2 0
4 2

(5 行受影响)

--*/
LouisXIV 2006-06-28
  • 打赏
  • 举报
回复
--修改一下

if object_id('testtable') is not null drop table testtable
go
create table testtable
(
fid int,
fparentid int
)
insert into testtable
select 1,0 union all
select 2,0 union all
select 3,1 union all
select 4,2 union all
select 5,3
go
if object_id('f_test') is not null drop function f_test
go
create function f_test(@a int)
returns int
as
begin
declare @r int
set @r=@a
while not exists (select 1 from testtable where fparentid=0 and fid=@r)
and exists (select 1 from testtable where fid=@r)
select @r=fparentid from testtable where fid=@r
return @r
end
go
select *
from testtable
order by dbo.f_test(fid),fparentid

/*
fid fparentid
----------- -----------
1 0
3 1
5 3
2 0
4 2
*/
LouisXIV 2006-06-28
  • 打赏
  • 举报
回复
--lz给的示例有问题

if object_id('testtable') is not null drop table testtable
go
create table testtable
(
fid int,
fparentid int
)
insert into testtable
select 1,0 union all
select 2,0 union all
select 3,1 union all
select 4,2 union all
select 5,3
go
if object_id('f_test') is not null drop function f_test
go
create function f_test(@a int)
returns int
as
begin
declare @r int
set @r=@a
while not exists (select 1 from testtable where fparentid=0 and fid=@r)
and exists (select 1 from testtable where fid=@r)
select @r=fparentid from testtable where fid=@r
return @r
end
go
select *
from testtable
order by dbo.f_test(fid)

/*
fid fparentid
----------- -----------
1 0
3 1
5 3
4 2
2 0
*/

22,206

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧