Tuesday, February 26, 2013

Fetch categories and sub Categories from single table

SQL Table:

 I have created a single table for categories and sub categories. This query support for multilevel subcategories


Query for fetch categories and sub Categories:


A single query for fetch categories and sub Categories from Categories table

WITH CategoryView (catid, parentid, categoryname) AS
(
  SELECT ID, ParentID, cast(CategoryName as varchar(255)) 
  FROM [Categories]
  WHERE ParentID = 0

  UNION ALL

  SELECT C.ID, C.ParentID, cast(CV.categoryname+'/'+C.CategoryName as varchar(255))
  FROM [Categories] C
  JOIN CategoryView CV ON CV.catID = C.ParentID
)
SELECT * FROM CategoryView ORDER BY categoryname

Result Preview: