We have following records in our table.
We want output should come in this format.
This is best example of hierarchical query.
Let’s try to write it.
T-SQL
CREATE TABLE TableCTE (ID int, ParentID int NULL, Name varchar(128));INSERT INTO TableCTE VALUES (1, NULL, 'A');INSERT INTO TableCTE VALUES (2, 1, 'B');INSERT INTO TableCTE VALUES (3, 2, 'C');INSERT INTO TableCTE VALUES (4, 3, 'D');INSERT INTO TableCTE VALUES (5, 4, 'E');SELECT * FROM TableCTEWITH Parent AS(SELECTID,ParentID,Name,Name AS PathFROMTableCTEWHEREParentID IS NULLUNION ALLSELECTTH.ID,TH.ParentID,TH.Name,CONVERT(varchar(128), Parent.Path + ',' + TH.Name) AS PathFROMTableCTE THINNER JOINParentONParent.ID = TH.ParentID)SELECT * FROM Parent
That’s It.
Enjoy Learning.
1 comment:
Thanks i was searching for it
Post a Comment