I have the following Location table
ID Name ParentID
-----------------------
1 TopLevel NULL
2 Region 1 1
3 Fleet 1 2
4 Fleet 2 2
I have just recently finished up writing a recursive CTE to display this structure in a hierarchy approach:
TopLevel
-Region 1
--Fleet 1
--Fleet 2
I now need to write a query to return this structure in a column hierarchal format:
Level1 Level2 Level3 Level4 Level5 Level6
Top Level
Top Level Region 1 Fleet 1
Top Level REgion 1 Fleet 2
The maximum levels deep a location can go is 9. How would I accomplish this? I was trying to use the recursive CTE and build on that, but I don’t think that is going to work. Any other ideas?
Here would be one method to accomplish the output, using a recursive CTE hard-coded to fill out up to 9 levels worth of hierarchy (you would need to change table/column references as necessary to your real object names, and you may need to increase
varchar(50)if the actual type ofnamecolumn is wider than that):Sample Output:
Demo: http://www.sqlfiddle.com/#!6/0bd5d/14