次のようなクエリを返そうとしています:
ルート 1
--> 子 2
------> 子 3
ルート 2
--> 子 4 --
> 子 5
したがって、クエリはルート 1 を 1 つの行として返し、 ---> 子 2 を別の行として返す必要があります。nレベルと仮定し、「--->」形式が各子に配置されます。レベルが上がると「---->」が増えます。
私のテーブルの定義は
[NodeId、ParentId、名前、レベル]
次のようなクエリを返そうとしています:
ルート 1
--> 子 2
------> 子 3
ルート 2
--> 子 4 --
> 子 5
したがって、クエリはルート 1 を 1 つの行として返し、 ---> 子 2 を別の行として返す必要があります。nレベルと仮定し、「--->」形式が各子に配置されます。レベルが上がると「---->」が増えます。
私のテーブルの定義は
[NodeId、ParentId、名前、レベル]
SQL Server 2008 以降では、hierarchyId データ型を使用して、必要な並べ替えをすばやく実現できます。REPLICATE() を使用してダッシュを取得できます。
;with cte as (
select NodeId, ParentId, Name, 0 Level, '/' + cast(NodeId as varchar(max)) + '/' Hier
from tbl1
where ParentId is null
union all
select t.NodeId, t.ParentId, t.Name, Level+1, Hier + cast(t.NodeId as varchar(max)) + '/'
from tbl1 t
join cte c on t.ParentId = c.NodeId
)
select case when level=0
then ''
else replicate('-',level*2) + '>' end + Name
from cte
order by cast(Hier as hierarchyid);
以前の SQL Server 2005 では、ゼロで埋められた文字列を使用して、hierarchyId の並べ替えをエミュレートできます。
;with cte as (
select NodeId, ParentId, Name, 0 Level, right(replicate('0',10)+cast(NodeId as varchar(max)),11) Hier
from tbl1
where ParentId is null
union all
select t.NodeId, t.ParentId, t.Name, Level+1, Hier + right(replicate('0',10)+cast(t.NodeId as varchar(max)),11)
from tbl1 t
join cte c on t.ParentId = c.NodeId
)
select case when level=0
then ''
else replicate('-',level*2) + '>' end + Name
from cte
order by Hier;