September 10, 2011

Concatenate Rows in SQL Server

We have following data in ItemDetails table.



Output should come in this format.


DECLARE @ItemsList TABLE
(
   ID        INT,
   Items    VARCHAR(40)
)
INSERT INTO @ItemsList
SELECT 1,'Printer'
UNION ALL
SELECT 1,'LCD'
UNION ALL
SELECT 1,'TFT'
UNION ALL
SELECT 2,'Printer'
UNION ALL
SELECT 2,'USB Drive'

SELECT * FROM @ItemsList

SELECT ID, STUFF((SELECT ',' + Items FROM @ItemsList IL1 where IL1.ID = IL2.ID FOR XML PATH('')),1,1,'') AS 'Items'
FROM (SELECT DISTINCT ID FROM @ItemsList) IL2

That’s It
Enjoy Learning.

No comments:

Post a Comment