Group and concatenate many rows to one

我们两清 提交于 2019-12-04 05:29:37

问题


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.


回答1:


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.




回答2:


I believe you're looking for something like this:

DECLARE @string nvarchar(max)
SET @string = N''

SELECT @string = @string + [Text] + N' ' FROM [YourTable]

SELECT @string

This will concatenate all of the values for the [Text] column into a single variable. You can then select the variable to retrieve all of the values in a single row.




回答3:


Something like:

DECLARE @result varchar(max)

SELECT @result = COALESCE(@result + ' ','') +[Text] FROM [Table]
SELECT @result


来源:https://stackoverflow.com/questions/3856224/group-and-concatenate-many-rows-to-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!