這裏將是一種完成輸出的方法,使用遞歸CTE硬編碼來填充高達9層的層次結構(您需要根據需要將表/列引用更改爲實際對象名稱,並且您可能需要增加varchar(50)
如果name
列的實際類型比)寬:
with cte as (
select id, 1 as level,
name as level1,
cast(null as varchar(50)) as level2,
cast(null as varchar(50)) as level3,
cast(null as varchar(50)) as level4,
cast(null as varchar(50)) as level5,
cast(null as varchar(50)) as level6,
cast(null as varchar(50)) as level7,
cast(null as varchar(50)) as level8,
cast(null as varchar(50)) as level9
from table1 t
where parentid is null
union all
select t.id, cte.level + 1 as level,
case when level = 0 then t.name else cte.level1 end as level1,
case when level = 1 then t.name else cte.level2 end as level2,
case when level = 2 then t.name else cte.level3 end as level3,
case when level = 3 then t.name else cte.level4 end as level4,
case when level = 4 then t.name else cte.level5 end as level5,
case when level = 5 then t.name else cte.level6 end as level6,
case when level = 6 then t.name else cte.level7 end as level7,
case when level = 7 then t.name else cte.level8 end as level8,
case when level = 8 then t.name else cte.level9 end as level9
from table1 t
inner join cte on cte.id = t.parentid
)
select * from cte;
樣本輸出:
| ID | LEVEL | LEVEL1 | LEVEL2 | LEVEL3 | LEVEL4 | LEVEL5 | LEVEL6 | LEVEL7 | LEVEL8 | LEVEL9 |
----------------------------------------------------------------------------------------------------
| 1 | 1 | TopLevel | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
| 2 | 2 | TopLevel | Region 1 | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
| 3 | 3 | TopLevel | Region 1 | Fleet 1 | (null) | (null) | (null) | (null) | (null) | (null) |
| 4 | 3 | TopLevel | Region 1 | Fleet 2 | (null) | (null) | (null) | (null) | (null) | (null) |
演示:http://www.sqlfiddle.com/#!6/0bd5d/14
你應該在應用程序方面這樣做。 – Kermit
沒有前端,全都在數據庫中。 – mameesh
它是如何「在數據庫中的所有」?所有關心行與列的最終用戶都在Management Studio中查看結果? –