Search code examples
sqljointreeviewcommon-table-expressionself

Tree view using SQL Query


I have a regions table of which I want a tree view (table simple ordered as tree) is it possible using sql queries help is appreciated, I tried to do it using self joins but i did not get the desired result.

enter image description here

tree view is something like this

Indiv

  • Div1
    • Zon1
  • div2
    • zon2
  • div3
    • zon3

EDIT:

as per Charles Bretana suggetion I tried CTE in below query and it did not give me desired result.

WITH Emp_CTE (id, ParentID, name)
AS (
SELECT id, ParentID, name
FROM eQPortal_Region
WHERE ParentID=0
UNION ALL
SELECT e.id, e.ParentID, e.name
FROM eQPortal_Region e
INNER JOIN Emp_CTE ecte ON ecte.id = e.ParentID
)
SELECT *
FROM Emp_CTE
GO

This is the result .. what went wrong ?

InDiv1

  • Div1
  • Div2
  • Div3
    • Zon3
    • Zon2
    • zon1

Solution

  • This guy Maulik Dhorajia answers the question perfectly ...

    http://maulikdhorajia.blogspot.com/2012/06/sql-server-using-ctecommon-table.html

    Made a replica of the query ..

    ;WITH CTECompany
    AS
    (
        SELECT 
        ID, 
        ParentID, 
        Name , 
        0 AS HLevel,
        CAST(RIGHT(REPLICATE('_',5) +  CONVERT(VARCHAR(20),ID),20) AS VARCHAR(MAX)) AS OrderByField
    FROM Region
    WHERE ParentID = 0
    
    UNION ALL
    
    SELECT 
        C.ID, 
        C.ParentID, 
        C.Name , 
        (CTE.HLevel + 1) AS HLevel,
        CTE.OrderByField + CAST(RIGHT(REPLICATE('_',5) +  CONVERT(VARCHAR(20),C.ID),20) AS VARCHAR(MAX)) AS OrderByField
    FROM Region C
    INNER JOIN CTECompany CTE ON CTE.ID = C.ParentID
    WHERE C.ParentID IS NOT NULL
    
    
    )
    
    -- Working Example
    SELECT 
    ID
    , ParentID
    , HLevel
    , Name
    , (REPLICATE( '----' , HLevel ) + Name) AS Hierachy
    FROM CTECompany
    ORDER BY OrderByField