CTE query doesn't print the right structure?
-
01-11-2019 - |
Question
I have this table which represents hierarchy :
childID parentID NAME siblingOrder
1 1 a 0
212 1 ab 1
112 1 ac 2
412 1 ad 3
-912 112 aca 0
The structure is:
a
+----ab
+----ac
+---aca
+----ad
(The siblingOrder
column is for controlling the order of ab
,ac
,ad
)
I already have this solution which uses the siblingOrder
:
;WITH CTE AS(
SELECT childID, parentID, 0 AS depth, NAME , siblingOrder,
CAST(RIGHT('00000' + CAST(siblingOrder AS VARCHAR(6)), 6) AS VARCHAR(1024)) AS PATH
FROM @myTable
WHERE childID = parentID
UNION ALL
SELECT TBL.childID, TBL.parentID,
CTE.depth + 1 , TBL.name ,TBL.siblingOrder,
CAST(cte.Path + '.' + RIGHT('00000' + CAST(Tbl.siblingOrder AS VARCHAR(6)), 6)AS VARCHAR(1024) )
FROM @myTable AS TBL
INNER JOIN CTE ON TBL.parentID = CTE.childID
WHERE TBL.childID<>TBL.parentID
)
SELECT path,depth, childID, parentID, siblingOrder, REPLICATE('----', depth) + name
FROM CTE
ORDER BY PATH
So order by
PATH
actually do the job :
The problem:
The problem is that I Must(!) put values in the siblingOrder
in order for it to work !
Otherwise , For example :
If I put 0
in all siblingOrder
this is the result :
(yes, now sorting by path - doesn't work...)
I need that aca
will always be under ac
(The only reason I added the siblingOrder
is to order siblings !) and I don't want to enforce adding siblingOrder
when not needed
Question :
Is it possible to enhance the query so that siblingOrder
will affect only to siblings ?
I mean , If I don't care about the order of the siblings ( by putting 0
) , I still expect the aca
to be under ac
No correct solution