16

I have a select query that returns one column and I want to convert that to string rows separated with ','

Select name 
from tblUsers

Gives a result:

Row1; asieh
Row2:amir
Row3:safoora

I want to return

Row1: asieh,amir,safoora
0

3 Answers 3

30

SQL Fiddle

MS SQL Server 2008 Schema Setup:

CREATE TABLE tblUsers
    ([name] varchar(7))
;

INSERT INTO tblUsers
    ([name])
VALUES
    ('asieh'),
    ('amir'),
    ('safoora')
;

Query 1:

    SELECT STUFF((
        select ','+ name 
        from tblUsers
        FOR XML PATH('')
        )
        ,1,1,'') AS names

Results:

|              NAMES |
|--------------------|
| asieh,amir,safoora |
Sign up to request clarification or add additional context in comments.

Comments

18

Here's a solution using variables:

DECLARE @out VARCHAR(MAX)
SELECT @out = COALESCE(@out+',' ,'') + name
FROM tblUsers
SELECT @lout

Comments

2

Try this :

Create Table #tblUsers ( Name Varchar(100) );
Insert Into #tblUsers Values ('Row1; asieh'),('Row2:amir'),('Row3:safoora')

Select Stuff((Select ',' + Name
                From #tblUsers
                 For Xml Path('')
       ), 1, 1, '' ) As ConcatenedString

drop table #tblUsers

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.