In a table there are the columns ID, Title and ParentID. ParentID is used for the ID of the entry in the same table which is considered its parent - thus any entry in which ParentID is NULL is one which is itself a parent.
I need a query which will iterate through each parent and list any child below it (ideally with a hyphen or something to denote its subordination) does anyone know how this can be done or how to point me in the right direction?
(I've looked into T-SQL and read many similar online questions however my SQL isn't quite sharp enough to make sense of it, so I'd greatly appreciate some pointers!)
Here you are!
WITH n(ID, Title) AS
(SELECT ID, Title
FROM YourTable
WHERE ID = (SELECT TOP 1 ID FROM YourTable WHERE ParentID IS NULL)
UNION ALL
SELECT nplus1.ID, nplus1.Title
FROM YourTable as nplus1, n
WHERE n.ID = nplus1.ParentID)
SELECT ID, Title FROM n
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With