1

I have got this table which has email address of 3 employees in SQL Server

Table structure is

EmployeeId, EmployeeName, Employee email address

Data is like this:

1   Conrad   Conrad@test.com

Output I need is the e-mail addresses in a single row / one column:

conrad@test.com; ali@test.com; will@test.com

Can someone please help.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Conrad Jagger
  • 643
  • 6
  • 19
  • 31
  • [**This**](http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-ms-sql-server-2005) might be helpful – Mahmoud Gamal Aug 29 '12 at 07:27

4 Answers4

3

You can try this: SQL Fiddle

SELECT SUBSTRING(
(SELECT ';' + e.EmailAddress
FROM Employee e
FOR XML PATH('')),2,8000) AS CSV

From SQL Server 2005 upward. See more here

codingbiz
  • 26,179
  • 8
  • 59
  • 96
1

FOR XML PATH() is good solution for SQL Server:

WITH x AS (
    SELECT 'x@example.com' AS mail
    UNION
    SELECT 'y@example.com'
    UNION
    SELECT 'z@example.com'
)
SELECT
    STUFF((SELECT
        mail + ','
    FROM
        x
    FOR XML PATH(''), TYPE, ROOT).value('root[1]', 'nvarchar(max)'), 1, 1, '')

Query above returns @example.com,y@example.com,z@example.com,.

In your case query would look like (could contain errors):

SELECT
  EmployeeId, 
  EmployeeName, 
  (SELECT
        STUFF((SELECT
            [e.email address] + ','
        FROM
            employees e
        WHERE
                e.EmployeeId = EmployeeId
        FOR XML PATH(''), TYPE, ROOT).value('root[1]', 'nvarchar(max)'), 1, 1, '')) AS mails
   FROM
     employees
jdphenix
  • 15,022
  • 3
  • 41
  • 74
Grzegorz Gierlik
  • 11,112
  • 4
  • 47
  • 55
1

You can try with COALESCE

DECLARE @listStr VARCHAR(MAX)

select @listStr = COALESCE(@listStr+',','') + Employee_email_address from table1 where EmployeeId = @EmployeeId
select @listStr

Query above will return @example.com,y@example.com,z@example.com,

jdphenix
  • 15,022
  • 3
  • 41
  • 74
Pankaj Agarwal
  • 11,191
  • 12
  • 43
  • 59
0

You can use cursor for that.

DECLARE @email VARCHAR(256) 
DECLARE @EmailCollection VARCHAR(MAX)

DECLARE db_cursor CURSOR FOR  
SELECT Email 
FROM tableName

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @email   

WHILE @@FETCH_STATUS = 0   
BEGIN   

       SET  @EmailCollection = @EmailCollection + @email + ';'
       FETCH NEXT FROM db_cursor INTO @email   
END   

CLOSE db_cursor   
DEALLOCATE db_cursor

And at the end you can return @EmailCollection

Usman Khalid
  • 3,032
  • 9
  • 41
  • 66