如何将列值以逗号分隔

时间:2014-03-19 04:50:01

标签: sql sql-server

如何在SQL Server中单独使用逗号分隔列值。下面显示的是我的SQL查询#

 select BandName from BandMaster where BandId<100 

我需要在单个查询中单独使用BandName值逗号。

4 个答案:

答案 0 :(得分:1)

Use XML path for this.

select (select BandName+',' from BandMaster where BandId<100 for xml path('')) as NewColumnName

Try this

答案 1 :(得分:0)

试试这个

SELECT BandName  = 
              STUFF ( ( SELECT ','+InrTab.BandName 
                        FROM [Table1] InrTab
                        WHERE InrTab.BandId= OutTab.BandId
                                            AND InrTab.BandId < 100                     
                        ORDER BY InrTab.BandId
                        FOR XML PATH(''),TYPE 
                       ).value('.','VARCHAR(MAX)') 
                      , 1,1,SPACE(0))
FROM [Table1] OutTab
GROUP BY OutTab.BandId;

答案 2 :(得分:0)

请试试这个

SELECT GROUP_CONCAT(BandName) from BandMaster where BandId<100

答案 3 :(得分:0)

Declare @retStr varchar(max) = ''
select @retStr = @retStr + BandName + ',' from BandMaster
where BandId<100 

Select @retStr