How to concatenate a list of names fast and easy in Sql Server

Scenario : We have a table that contains all the employees of our company and we want to take all their names and concatenate them separated by comma.

Solution :

DECLARE @result NVARCHAR(MAX)
SET @result = ''
 
SELECT   @result += Name + ','
FROM  dbo.Employee 

SET @result = LEFT(@result,LEN(@result)-1)

UPDATE : ——————————————————————— Faster solution –  tested on 100000 records : proposed by Cristina

SELECT top 1
NameList=STUFF((SELECT ‘,’+Name
FROM dbo.Employee FOR XML PATH(”)) , 1 , 1 , ” )
FROM
dbo.Employee

 

Powered by CodeReview – Let's make it Better!