First of all, please follow the link provided by
CHill60[
^].
Try this:
DECLARE @hierarchy TABLE (id INT IDENTITY(1,1), parent_id INT, name NVARCHAR(50))
INSERT INTO @hierarchy(parent_id, name)
VALUES(0, 'Sports'),
(0, 'Clothes'),
(0, 'Facial'),
(2, 'Mens'),
(0, 'Electronics'),
(2, 'Shirts'),
(3, 'Cream'),
(5, 'Mobile'),
(8, 'Apple')
;WITH CTE AS
(
SELECT id, parent_id, name, 1 AS distance, id as pid
FROM @hierarchy
WHERE parent_id = 0
UNION ALL
SELECT h.id, h.parent_id, h.name, distance + 1 AS distance, h.parent_id As pid
FROM @hierarchy h INNER JOIN CTE c ON c.id = h.parent_id
)
SELECT *
FROM CTE
ORDER BY pid, distance
As you can see, i've used small trick to return data in a correct order:
- in the first loop:
- i'm setting 1 as a distance
- i'm getting [id] from
@hierarchy
table as [pid]
- in every next loop:
- i'm calculating distance by adding 1
- i'm getting [parent_id] from
@hierarchy
table as [pid]