11

下面的代码(我从这里得到的)在将多个用逗号分隔的字段合并在一起方面做得很好。

select player,
  stuff((SELECT distinct ', ' + cast(score as varchar(10))
       FROM yourtable t2
       where t2.player = t1.player
       FOR XML PATH('')),1,1,'') 
from yourtable t1
group by player

我需要用回车换行替换逗号。我尝试了下面的代码,但它开始用这些字符分隔条目:“#x0D;”

select player,
  stuff((SELECT distinct CHAR(13)+CHAR(10) + cast(score as varchar(10))
       FROM yourtable t2
       where t2.player = t1.player
       FOR XML PATH('')),1,1,'') 
from yourtable t1
group by player

我怀疑问题出在“FOR XML PATH('')),1,1,''”,但我不知道要输入什么值。

任何帮助将不胜感激。

谢谢!

4

2 回答 2

11

您实际上可以替换 STUFF 结果上的逗号。

尝试这个:

select player,
  replace(stuff((SELECT distinct ', ' + cast(score as varchar(10))
       FROM yourtable t2
       where t2.player = t1.player
       FOR XML PATH('')),1,1,''), ',', char(13) + char(10))
from yourtable t1
group by player
于 2013-03-22T14:22:17.913 回答
4

您可以使用以下方法处理 XML 添加的所有特殊字符(其中#x0D;一个):

FOR XML PATH(''), TYPE).value('.','nvarchar(max)')

更多信息在这里

您还需要将第三个参数调整为STUFF在结果开始时需要跳过的字符数(在本例中为 2,因为您有char(13)and char(10))。

所以你的解决方案是:

select player,
  stuff((SELECT distinct CHAR(13)+CHAR(10) + cast(score as varchar(10))
       FROM yourtable t2
       where t2.player = t1.player
       FOR XML PATH(''), TYPE).value('.','nvarchar(max)'),1,2,'') 
from yourtable t1
group by player
于 2017-05-13T12:13:49.223 回答