/ Published in: SQL
to fetch all the children in a tree based on parentid
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
http://stackoverflow.com/questions/926033/in-sql-server-how-can-i-select-all-records-in-a-recursive-TABLE inline code IF url IS NOT working: CREATE TABLE TestTable ( ID INT PRIMARY KEY NOT NULL, ParentID INT ) INSERT INTO TestTable VALUES (0, NULL) INSERT INTO TestTable VALUES (1, 0) INSERT INTO TestTable VALUES (2, 0) INSERT INTO TestTable VALUES (3, 1) INSERT INTO TestTable VALUES (4, 3) -- Get branch ;WITH TreeRecCTE (ID, ParentID, IDPath) AS ( SELECT ID, ParentID, CONVERT(VARCHAR(MAX), ID) AS IDPath FROM TestTable WHERE ParentID IS NULL UNION ALL SELECT Child.ID, Child.ParentID, Parent.IDPath + '.' + CONVERT(VARCHAR(100),Child.ID) AS IDPath FROM TestTable AS Child INNER JOIN TreeRecCTE AS Parent ON Child.ParentID = Parent.ID ) SELECT * FROM TreeRecCTE WHERE IDPath LIKE '%.1.%' ORDER BY ParentID ASC -- Get complete tree: ;WITH TreeRecCTE (ID, ParentID, IDPath) AS ( SELECT ID, ParentID, CONVERT(VARCHAR(MAX), ID) AS IDPath FROM TestTable WHERE ParentID IS NULL UNION ALL SELECT Child.ID, Child.ParentID, Parent.IDPath + '.' + CONVERT(VARCHAR(100),Child.ID) AS IDPath FROM TestTable AS Child INNER JOIN TreeRecCTE AS Parent ON Child.ParentID = Parent.ID ) SELECT * FROM TreeRecCTE ORDER BY ParentID ASC