1

我有这张表,其中包含 SQL Server 中 3 名员工的电子邮件地址

表结构是

EmployeeId, EmployeeName, Employee email address

数据是这样的:

1   Conrad   Conrad@test.com

我需要的输出是单行/一列中的电子邮件地址:

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

有人可以帮忙吗。

4

4 回答 4

3

你可以试试这个:SQL Fiddle

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

从 SQL Server 2005 开始。在这里查看更多

于 2012-08-29T07:27:36.097 回答
1

FOR XML PATH()是 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, '')

上面的查询返回@example.com,y@example.com,z@example.com,

在您的情况下,查询看起来像(可能包含错误):

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
于 2012-08-29T07:29:34.457 回答
1

你可以试试COALESCE

DECLARE @listStr VARCHAR(MAX)

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

上面的查询会返回@example.com,y@example.com,z@example.com,

于 2012-08-29T07:36:46.733 回答
0

您可以为此使用光标。

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

最后你可以返回@EmailCollection

于 2012-08-29T07:32:14.063 回答