Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table [Charts] contains value in column [name] like FLOWERS, ANIMALS,GAMES and their name table looking like this
<pre>Id					Name			ParentId
1					FLOWERS			0
2					rose			1
3					lily			1
4					lotus			1
5					ANIMALS			0
6					dog				5
7					cat				5
8					rat				5
9					monkey			5
10					GAMES			0
11					cricket			10
12					football		10
13					basketball		10
14					badminton		10



I need output like this
Name		Id
Flowers		2,3,4
Animals		6,7,8,9
Games		11,12,13,14


What I have tried:

Do i have to create any sql function
Posted
Updated 18-Jul-19 5:34am

What you want to do is read up on Concatenation
Concatenating Row Values in Transact-SQL - Simple Talk[^]

This example is similar to the XML tricks, sorry I didn't play too much with it to work out the INT vs VARCHAR
SQL
declare @table table (
  ID  varchar(16)
, ParentID  varchar(16)
, [Name] varchar(16)
)

insert @table
values (1, 0, 'FLOWERS'), (2, 1, 'rose'), (3, 1, 'lily')
, (4, 1, 'lotus'), (5, 0, 'ANIMALS'), (6, 5, 'dog'), (7, 5, 'cat')
, (8, 5, 'rat'), (9, 5, 'monkey'), (10, 0, 'GAMES'), (11, 10, 'cricket')
, (12, 10, 'football'), (13, 10, 'basketball'), (14, 10, 'badminton')

SELECT p.[Name]
,      Children = SUBSTRING( (
         SELECT ','+c.ID  AS [text()]
         FROM @table c
         WHERE c.ParentID = p.ID
         ORDER BY c.ID
         FOR XML PATH ('')
        ), 2, 1000)
FROM     @table p
WHERE    p.ParentID = 0
order by p.ID
But it does give the results you want
Name      Children
--------  ---------
FLOWERS   2,3,4
GAMES     11,12,13,14
ANIMALS   6,7,8,9
 
Share this answer
 
Comments
Richard Deeming 18-Jul-19 12:23pm    
Only one CAST call required to make it work with int columns:
SELECT ',' + CAST(c.ID As varchar(max))  AS [text()]

:)
Write a SQL stored procedure that returns all the rows from the table. Then write some code that iterates through the rows. Whenever it encounters a row with a ParentId of 0 it outputs the ID of the following rows until it next encounters a row with a ParentId of 0. And so on. I've done something almost identical to this when building a menu tree structure from our menu table.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900