11

The code below (which I got from here ) does a good job at merging together multiple fields separating them with commas.

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

I need to replace the commas with carriage return line feeds. I tried the code below but it started separating the entries with these characters: "#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

I suspect the problem is with the "FOR XML PATH('')),1,1,''" but I don't know what values to put.

Any help would be greatly appreciated.

Thanks!

Community
  • 1
  • 1
Osprey
  • 1,523
  • 8
  • 27
  • 44

2 Answers2

11

You can actually replace the comma on the result of STUFF.

Try this:

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
jerjer
  • 8,694
  • 30
  • 36
4

You can handle all the special characters that XML adds (of which #x0D; is one) by using:

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

More information here.

You will also need to adjust the third parameter of STUFF to the number of characters you need to skip at the start of your result (in this case to 2 because you have char(13) and char(10)).

So your solution would be:

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
Community
  • 1
  • 1
jhnpckr
  • 108
  • 1
  • 7