Reputation: 1070
I need to combine the column result of multiple rows into one variable. A sample of my dataset can be found below.
EmailAddress
-------------
[email protected]
[email protected]
Currently, I am using STUFF to combine the EmailAddress
column into a semicolon delimited list.
A sample can be seen below.
SELECT @EmailAddress = CONVERT(nvarchar(max)
, STUFF(
(SELECT ';' + EmailAddress FROM EmployeeCourseDetails)
, 1
, 1
, '')
)
The desired result should look like [email protected];[email protected]
but when I execute the statement, I get the following error: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Any help please?
Upvotes: 1
Views: 1619
Reputation: 834
I did something similar once with FOR XML PATH('')
.
Like this:
SELECT @EmailAddress = CONVERT(nvarchar(max)
, STUFF(
(SELECT ';' + EmailAddress FROM EmployeeCourseDetails FOR XML PATH(''))
, 1
, 1
, '')
)
Upvotes: 1
Reputation: 460048
You can use COALESCE
:
DECLARE @EmailAddress VARCHAR(8000)
SELECT @EmailAddress = COALESCE(@EmailAddress + ';', '') + EmailAddress
FROM EmployeeCourseDetails
ORDER BY EmailAddress
SELECT @EmailAddress
Result: [email protected];[email protected]
Upvotes: 1