What is the meaning of SELECT … FOR XML PATH(‘ ‘),1,1)?

There’s no real technique to learn here. It’s just a cute trick to concatenate multiple rows of data into a single string. It’s more a quirky use of a feature than an intended use of the XML formatting feature.

SELECT ',' + ColumnName ... FOR XML PATH('')

generates a set of comma separated values, based on combining multiple rows of data from the ColumnName column. It will produce a value like ,abc,def,ghi,jkl.

STUFF(...,1,1,'')

Is then used to remove the leading comma that the previous trick generated, see STUFF for details about its parameters.

(Strangely, a lot of people tend to refer to this method of generating a comma separated set of values as “the STUFF method” despite the STUFF only being responsible for a final bit of trimming)

Leave a Comment