Thursday, April 14, 2011

Selecting a Comma Seperated List

Hello All,

Sometimes we required a comma separated value instead of table. So generally people make User define functions or Cursors or loop but there is a really very simple way to do this in a simple select statement.

See the below query

DECLARE @Users varchar(MAX)
SET @Users = ''
SELECT @Users = @Users + CONVERT(NVARCHAR(50),firstname) + ','
FROM UserDetails
SET @Users = LEFT(@Users,LEN(@Users)-1)
SELECT @Users as users