2013-03-22 11 views
7

Il codice seguente (ottenuto da here) fa un buon lavoro nell'unire più campi separandoli con virgole.Unione di più righe in una colonna utilizzando i feed di ritorno a capo del carrello

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 

Ho bisogno di sostituire le virgole con avanzamento linea di ritorno a capo. Ho provato il codice qui sotto ma ha iniziato a separare le voci con questi caratteri: "# 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 

ho il sospetto che il problema è con il "FOR XML PATH ('')), 1,1, ''", ma non so quali valori mettere.

Qualsiasi aiuto sarebbe molto apprezzato.

Grazie!

risposta

8

In realtà è possibile sostituire la virgola sul risultato di STUFF.

Prova questo:

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 
+0

ha funzionato! Grazie! :) – Osprey

+0

che ne dici di passare a una nuova riga anziché a una virgola? –

3

è possibile gestire tutti i caratteri speciali XML aggiunge (di cui è uno #x0D;) utilizzando:

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

Maggiori informazioni here.

sarà anche necessario per regolare il terzo parametro di STUFF al numero di caratteri necessari per saltare all'inizio del vostro risultato (in questo caso per 2 perché avete char(13) e char(10)).

Quindi la soluzione sarebbe:

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 
Problemi correlati