Sunday, 20 November 2016

SQL Server select results as string separated with ','




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

Answer



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 |

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...