SQL Server – Group and Concatenate Many Rows to One

sqlsql-serversql-server-group-concat

I want to "concatenate" all the "Text"-rows into one single row and get one row as a result. Is this even possible? I use MSSQL Server 2005.

query

Best Answer

Use FOR XML PATH:

SELECT [Text]+' ' AS 'text()' FROM _table FOR XML PATH('')

Another option - use string concatenation:

DECLARE @s nvarchar(max)
SELECT @s = ISNULL(@s, '') + t + ' '  FROM _table OPTION (MAXDOP 1)
SELECT @s

Please note that the latter one isn't guaranteed to work, afaik, officially the behaviour of "@s = @s + ..." for multi-row resultset is undefined.
MAXDOP 1 hint is used here to prevent the optimizer from creating a parralel execution plan, as this will yield an incorrect result for sure.

Related Question