Store And Retrive Hierarchical Data In SQL

First of all create to store hierarchical data in sql database
  1. CREATE TABLE [dbo].[TBL_Tree](  
  2. [Id] [int] IDENTITY(1,1) NOT NULL,  
  3. [ParentId] [intNULL,  
  4. [Name] [varchar](50) NULL,  
  5. [IsDisplay] [bitNULL,  
  6. CONSTRAINT [PK_TBL_Tree] PRIMARY KEY CLUSTERED  
  7. (  
  8. [Id] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY]  
  11. GO  
Now add below records in table
  1. SET IDENTITY_INSERT [dbo].[TBL_Tree] ON  
  2. GO  
  3. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (1, NULL, N'A'NULL)  
  4. GO  
  5. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (2, NULL, N'B'NULL)  
  6. GO  
  7. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (3, 1, N'A1'NULL)  
  8. GO  
  9. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (4, 1, N'A2'NULL)  
  10. GO  
  11. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (5, 1, N'A3'NULL)  
  12. GO  
  13. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (6, 2, N'B1'NULL)  
  14. GO  
  15. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (7, 2, N'B2'NULL)  
  16. GO  
  17. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (8, 3, N'A11'NULL)  
  18. GO  
  19. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (9, 3, N'A12'NULL)  
  20. GO  
  21. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (10, 7, N'B21'NULL)  
  22. GO  
  23. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (11, 7, N'B22'NULL)  
  24. GO  
  25. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (12, 9, N'A121'NULL)  
  26. GO  
  27. INSERT [dbo].[TBL_Tree] ([Id], [ParentId], [Name], [IsDisplay]) VALUES (13, 9, N'A122'NULL)  
  28. GO  
  29. SET IDENTITY_INSERT [dbo].[TBL_Tree] OFF  
  30. GO  
Now retrieve hierarchical data from sql using CTE
  1. With ItemGroup as  
  2. (  
  3. Select BI.Id,Bi.ParentId,Bi.Name, 1 as IGLevel From TBL_Tree BI where ISNULL(BI.ParentId,0)=0  
  4. Union All  
  5. Select BIN.Id,BiN.ParentId,BiN.Name, IG.IGLevel +1 From TBL_Tree BIN  
  6. Inner Join ItemGroup IG on (BIN.ParentId = IG.Id )  
  7. )  
  8. Select * From ItemGroup order by IGLevel, ParentId