Reputation: 5
I'm new in SQL Server. I just want to write a Stored procedure for this :
I don't know how many rows are there in the table. I want to group X
and Z
column and put together Y
column's text belonged to X
and Z
column.
I can make this with two loop. Is there any short way i can use in SQL Server.
Upvotes: 0
Views: 87
Reputation: 4192
Use STUFF
String function :
CREATE TABLE #table(X VARCHAR(10), Y VARCHAR(10) , name VARCHAR(10))
INSERT INTO #table(X , name , Y )
SELECT 'a','as','b' UNION ALL
SELECT 'a','ad','b' UNION ALL
SELECT 'a','de','b' UNION ALL
SELECT 'b','aa','c' UNION ALL
SELECT 'b','ss','c' UNION ALL
SELECT 'e','ew','r' UNION ALL
SELECT 'e','w','r' UNION ALL
SELECT 'e','ss','r' UNION ALL
SELECT 'e','dd','r'
SELECT T1.X X , STUFF( ( SELECT ' ' + name FROM #table T2 WHERE T1.X = T2.X
AND T1.Y = T2.Y FOR XML PATH('') ) ,1,2,'') Y , T1.Y Z
FROM #table T1
GROUP BY X , Y
Upvotes: 1