我有select
查询返回一列,我想将其转换为以','分隔的字符串行
Select name
from tblUsers
给出结果:
Row1; asieh
Row2:amir
Row3:safoora
我想返回
Row1: asieh,amir,safoora
答案 0 :(得分:17)
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