1

我需要将多行的列结果合并到一个变量中。我的数据集示例可以在下面找到。

EmailAddress
-------------
myemail@here.com
youremail@here.com

目前,我正在使用 STUFF 将该EmailAddress列组合成一个分号分隔的列表。可以在下面看到一个示例。

SELECT @EmailAddress = CONVERT(nvarchar(max)    
              , STUFF(
                  (SELECT ';' + EmailAddress FROM EmployeeCourseDetails)
                , 1
                , 1
                , '')
              )

期望的结果应该是这样myemail@here.com;youremail@here.com的,但是当我执行语句时,我收到以下错误:Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

请问有什么帮助吗?

4

2 回答 2

1

您可以使用COALESCE

DECLARE @EmailAddress VARCHAR(8000) 

SELECT   @EmailAddress = COALESCE(@EmailAddress + ';', '') + EmailAddress
FROM     EmployeeCourseDetails
ORDER BY EmailAddress

SELECT @EmailAddress

DEMO

结果:myemail@here.com;youremail@here.com

于 2013-09-26T14:13:09.293 回答
1

我曾经做过类似的事情FOR XML PATH('')。像这样:

SELECT @EmailAddress = CONVERT(nvarchar(max)    
              , STUFF(
                  (SELECT ';' + EmailAddress FROM EmployeeCourseDetails FOR XML PATH(''))
                , 1
                , 1
                , '')
              )
于 2013-09-26T14:13:28.437 回答