10

我有一个select返回一列的查询,我想将其转换为用“,”分隔的字符串行

Select name 
from tblUsers

给出一个结果:

Row1; asieh
Row2:amir
Row3:safoora

我想回来

Row1: asieh,amir,safoora
4

3 回答 3

22

SQL小提琴

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

结果

|              NAMES |
|--------------------|
| asieh,amir,safoora |
于 2013-09-09T16:41:41.543 回答
15

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

DECLARE @out VARCHAR(MAX)
SELECT @out = COALESCE(@out+',' ,'') + name
FROM tblUsers
SELECT @lout
于 2013-09-09T16:33:39.273 回答
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
于 2013-09-09T16:43:58.473 回答