如何获得一个查询的结果,该查询的结果是由一个分隔符分隔的一行中的多行?

时间:2013-04-08 13:37:39

标签: sql-server

我需要将一个查询的值作为单行获取,由一个分隔符分隔,但是我选择了它,但这有点棘手。

所以,我有:

select employer from employers

我会回来的:

(line1)    Anne
(line2)    Sue
(line3)    Villy
(line4)    John
(nth line) Marry

我需要得到这样的结果:

'Anne','Sue','Villy','John','Marry'

或者至少:

 Anne^Sue^Villy^John^Marry

任何提示? 谢谢,

2 个答案:

答案 0 :(得分:2)

declare @s varchar(max) = ''

select @s = case 
    when @s <> '' then  
        @s + ',''' + employer + ''''
    else 
        @s + '''' + employer + '''' end 
from employers

select @s

答案 1 :(得分:2)

SELECT STUFF((SELECT DISTINCT  ', ' + Employer AS [text()]
FROM Employers
FOR XML PATH ('')),1,1,'')