SQL Server - 在单行中返回多个行值

时间:2012-08-29 07:17:31

标签: sql sql-server

我的这个表在SQL Server中有3名员工的电子邮件地址

表结构是

EmployeeId, EmployeeName, Employee email address

数据是这样的:

1   Conrad   Conrad@test.com

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

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

有人可以帮忙。

4 个答案:

答案 0 :(得分:2)

您可以尝试:SQL Fiddle

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

从SQL Server 2005向上。 See more here

答案 1 :(得分: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

答案 2 :(得分: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,

答案 3 :(得分: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