SQL Server选择结果为字符串,以','分隔

时间:2013-09-09 16:30:57

标签: sql-server

我有select查询返回一列,我想将其转换为以','分隔的字符串行

Select name 
from tblUsers

给出结果:

Row1; asieh
Row2:amir
Row3:safoora

我想返回

Row1: asieh,amir,safoora

3 个答案:

答案 0 :(得分:17)

SQL Fiddle

MS SQL Server 2008架构设置

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

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

查询1

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

<强> Results

|              NAMES |
|--------------------|
| asieh,amir,safoora |

答案 1 :(得分:15)

这是使用变量的解决方案:

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

答案 2 :(得分:2)

试试这个:

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