Click here to Skip to main content
15,885,782 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a normalized table having data like this
C#
Gid         Gname

1           dance

2           cricket

3           football

In my table i am saving data like this
C#
ID   GID     SID

1    1,3     101

2     3      102

3    1,2,3   103

I want output like this
C#
SID   GName

101   dance,football

102   football

103   dance,cricket,football

Who can i write this query in sql 2008
Posted
Updated 1-Sep-13 22:41pm
v2

1 solution

U can do it in two ways... Either Using Fnsplitter Function or joins...
SQL
Create Table #Temp
	(
	Id int, 
	Gid Nvarchar(40),
	Sid Nvarchar(40) 
	)

Create Table #Dept
	(
	Gid Nvarchar(40),
	Gname Nvarchar(40) 
	)

Insert into #Temp 
Select 1,'1,3','101' Union all
Select 2,'3','102' Union all
Select 3,'1,2,3','103' 

Insert into #Dept 
Select '1','dance' Union All
Select '2','cricket' Union All
Select '3','football'

-- If u have fnsplitter u can use this....
--Select t.Sid,Stuff((Select ','+Gname From #Dept 
--		      Where Gid In (Select ID From fnSplitter(t.Gid)) 
--	For XML Path(''), TYPE).value('.','VARCHAR(max)'), 1, 1, '') [Gname] 
--From #Temp t

-- With out Fnsplitter
SELECT e.Sid, STUFF((SELECT ',' + d.Gname FROM #Dept AS d
		     INNER JOIN #Temp AS t
		   ON ',' + t.Gid + ',' LIKE '%,' + CONVERT(VARCHAR(12), d.Gid) + ',%'
		   WHERE t.Gid = e.Gid
		   ORDER BY Gname
		   FOR XML PATH, TYPE).value('.', 'nvarchar(max)'), 1, 1, '') as Gname
FROM #Temp AS e
ORDER BY Sid;

Drop Table #Temp
Drop Table #Dept 

Output:
SQL
Sid	Gname
-----   ---------
101	dance,football
102	football
103	cricket,dance,football
 
Share this answer
 
v4
Comments
RedDk 2-Sep-13 19:44pm    
RS ... smokes another one! Supa dupa!
Raja Sekhar S 3-Sep-13 0:52am    
Thanks...

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