1

I have a table as shown below.

ID ParentID Node Name  Node Type
------------------------------------------------------------------
525 524  Root   Area Level 1
526 525  C   Area Level 2
527 525  A   Area Level 2
528 525  D   Area Level 2
671 525  E   Area Level 2
660 527  B   Area Level 3
672 671  F   Area Level 3

How can i write a recursive t-sql query to generate below output?

Output ("Root" node not required in the output):

Node  ID
-----------------------
A  527
A/B  660
C  526
D  528
E  671
E/F  672

Thanks

2
  • And will you only need two levels or could there be data where a relates to b relates to c? Commented Jan 7, 2010 at 21:47
  • sql server 2005. There could be more than 2 levels Commented Jan 7, 2010 at 21:49

3 Answers 3

9

Take a look at this page on using common table expressions. That is what I would use (assuming you are using at least SQL Server 2005)

Here is a code example using your case:

 WITH CTE (NodePath, ID) AS (
    SELECT
        '/' + CAST(NodeName AS NVARCHAR(MAX)) AS NodePath,
        ID
    FROM TABLE
    WHERE NodeName = 'Root'

    UNION ALL

    SELECT
        CTE.NodePath + '/' + CAST(NodeName AS NVARCHAR(MAX)) AS NodePath,
        TABLE.ID
    FROM CTE
    INNER JOIN TABLE ON TABLE.ParentId = CTE.ID
)

SELECT
    NodeName,
    ID
FROM CTE
Sign up to request clarification or add additional context in comments.

2 Comments

@Gabriel, +1, I just wrote same sample code to update my previous answer =)
is it possible i can do something like "SELECT NodeName, ID FROM CTE" some way to pass level value to this
0

Recursion in SQL for SQL Server is described and demontrated here:

http://www.informit.com/guides/content.aspx?g=sqlserver&seqNum=90

And here:

http://www.vbforums.com/showthread.php?t=366078

and here:

http://msdn.microsoft.com/en-us/library/ms186243.aspx

Comments

0

You could also to take a look on Common Table Expressions (CTE) in SQL Server 2005

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.