Create Table emp
IDint,
parentID int
insert into emp values(1 , 0)
insert into emp values(5 , 3)
insert into emp values(3 , 1)
insert into emp values(4 , 2)
insert into emp values(2 , 1)
--按id拼个路径出来,然后按路径排序即可
--这是mssql的写法,db2我不知道
--search BREADTH first by ID set sort,估计是按用来产生排序的
With Report(ParentID,ID,Level)
As
Select parentID,ID,Convert(Varbinary(Max),id)
From emp Where parentID='0'
Union All
Select emp.parentID,emp.ID,Level+Convert(Varbinary,emp.id)
From report Join emp
On emp.parentID=report.ID
Select ID,parentID From report
Order By Level
--或者
With Report(ParentID,ID,Level)
As
Select parentID,ID,Convert(Varchar(Max),Right('00000'+id,5))
From emp Where parentID='0'
Union All
Select emp.parentID,emp.ID,Level+'-'+Convert(Varchar(Max),Right('00000'+emp.id,5))
From report Join emp
On emp.parentID=report.ID
Select ID,parentID From report
Order By Level