SQL Server select results as string separated with ','
本问题已经有最佳答案,请猛点这里访问。
我有一个返回一列的
1 2 | Select name from tblUsers |
给出了一个结果:
1 2 3 | Row1; asieh Row2:amir Row3:safoora |
我想回来
1 | Row1: asieh,amir,safoora |
SQL小提琴
MS SQL Server 2008架构安装程序:
1 2 3 4 5 6 7 8 9 10 11 | CREATE TABLE tblUsers ([name] varchar(7)) ; INSERT INTO tblUsers ([name]) VALUES ('asieh'), ('amir'), ('safoora') ; |
查询1:
1 2 3 4 5 6 | SELECT STUFF(( select ','+ name from tblUsers FOR XML PATH('') ) ,1,1,'') AS names |
结果:
1 2 3 | | NAMES | |--------------------| | asieh,amir,safoora | |
下面是一个使用变量的解决方案:
1 2 3 4 | DECLARE @out VARCHAR(MAX) SELECT @out = COALESCE(@out+',' ,'') + name FROM tblUsers SELECT @lout |
试试这个:
1 2 3 4 5 6 7 8 9 | 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 |