我需要将多行的列结果合并为一个变量。 我的数据集样本可以在下面找到。
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.
请帮忙吗?
答案 0 :(得分:1)
您可以使用COALESCE
:
DECLARE @EmailAddress VARCHAR(8000)
SELECT @EmailAddress = COALESCE(@EmailAddress + ';', '') + EmailAddress
FROM EmployeeCourseDetails
ORDER BY EmailAddress
SELECT @EmailAddress
结果:myemail@here.com;youremail@here.com
答案 1 :(得分:1)
我用FOR XML PATH('')
做过类似的事情。
像这样:
SELECT @EmailAddress = CONVERT(nvarchar(max)
, STUFF(
(SELECT ';' + EmailAddress FROM EmployeeCourseDetails FOR XML PATH(''))
, 1
, 1
, '')
)