SQL上String.Join的等价物是什么?

时间:2011-05-29 21:06:31

标签: sql-server tsql

  

可能重复:
  Is there a way to create a SQL Server function to “join” multiple rows from a subquery into a single delimited field?

大家好!

我正在寻找一种简单的方法来连接'n'值。类似的东西:

SELECT MyConcat(',', T.TextColumn)
FROM SomeTable AS T
WHERE T.SomeOtherColumn = SomeCondition

所以,如果我有一个像这样的表:

SomeTable:
Id  | TextColumn | SomeOtherColumn
----+------------+----------------
1   | Qwerty     | Y
2   | qwerty     | N
3   | azerty     | N
4   | Azerty     | Y

这会导致类似:

SQL:
SELECT MyConcat(';', T.TextColumn)
FROM SomeTable AS T
WHERE T.SomeOtherColumn = 'Y'

RESULT:
'Qwerty;Azerty'

2 个答案:

答案 0 :(得分:40)

这应该可以解决问题:

DECLARE @Result VARCHAR(MAX);

SELECT
    @Result = CASE
        WHEN @Result IS NULL
        THEN T.TextColumn
        ELSE @Result + ';' + T.TextColumn
    END
FROM
    SomeTable AS T
WHERE
    T.SomeOtherColumn = 'Y';

SELECT @Result

答案 1 :(得分:29)

SELECT CAST(TextColumn + ';' AS VARCHAR(MAX)) 
FROM SomeTable
WHERE SomeOtherColumn = 'Y'
FOR XML PATH ('')

如果你不喜欢尾随;,你可以从结果中删除字符。


2017年编辑

现在许多平台都支持窗口函数LISTAGG()