1

Possible Duplicate:
How do I Create a Comma-Separated List using a SQL Query?

I am working on a web application. I need the SQL query of single column selection like

select 
  recordid 
from 
  device 
where 
  accountid in (1,2)) 

I need this result to be formatted comma separated string from SQL.

0

4 Answers 4

5
DECLARE @Concat varchar(max)

select @Concat = CAST(recordid as varchar(10)) + coalesce(',' + @Concat , '')
 from device 
 where accountid in (1,2)

 SELECT @Concat
Sign up to request clarification or add additional context in comments.

1 Comment

Smart way of avoid unnecessary commas...
3

You can use something like this:

DECLARE @result AS VARCHAR(MAX)

SET @result = '' -- initialize with empty string to avoid NULL result

SELECT
  @result = @result + ',' + CAST(recordid AS VARCHAR)
FROM
  device
WHERE
  accountid IN (1,2)


SELECT @result AS recordids

Comments

2

This is covered in detail in other questions, including:

Comments

0

You can also write a custom CLR aggregate function which can end up being more optimized than using string concatenation (especially with a really large result set).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.