2

I want to know the algorithm behind child nested records are displayed within parent nested records for example

Comment 1 (parent record)
reply 1 (child record)
reply 2 (child record)
reply 3 (child record)
view all

Comment 2 (parent record)
reply 1 (child record)
reply 2 (child record)
reply 3 (child record)
view all

how is a query written to get the above results?

i_user
  • 511
  • 1
  • 4
  • 21

1 Answers1

2

You can use a Recursive Common Table Expression like the one below

;WITH comments AS 
(
    SELECT 1 as ID,'Comment 1' detail,NULL AS ParentID
    UNION ALL SELECT 2 as ID,'Comment 2',NULL AS ParentID
    UNION ALL SELECT 3 as ID,'Reply 1',1 AS ParentID
    UNION ALL SELECT 4 as ID,'Reply 2',3 AS ParentID
    UNION ALL SELECT 5 as ID,'Reply 3',4 AS ParentID
    UNION ALL SELECT 6 as ID,'Reply 4',2 AS ParentID
    UNION ALL SELECT 7 as ID,'Reply 5',6 AS ParentID
),comment_hierarchy AS 
(
    SELECT ID,detail,ID AS prid,0 AS orderid
    FROM comments
    WHERE ParentID IS NULL
    UNION ALL 
    SELECT c.ID,c.detail ,ch.prid as prid,ch.orderid + 1
    FROM comments c
    INNER JOIN comment_hierarchy ch
    ON c.ParentID = ch.ID
)
SELECT ID,Detail
FROM comment_hierarchy
ORDER BY prid,orderid asc

For more info refer

https://technet.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx

CTE to get all children (descendants) of a parent

Community
  • 1
  • 1
ughai
  • 9,830
  • 3
  • 29
  • 47