无法将许多行连接到单个文本字符串sql server 2008中

时间:2018-01-15 16:19:01

标签: sql sql-server-2008 string-aggregation

如果没有XML函数,还有其他方法吗?我试过跟Concatenate many rows into a single text string? 我在尝试在SQL Server 2008 R2上运行时遇到问题。

将varchar值','转换为数据类型int。

时转换失败
Select distinct ST2.id 
    substring(
        (
            Select ','+ST1.id AS [text()]
            From dbo.idstable ST1
            Where ST1.id = ST2.id
            ORDER BY ST1.id
            For XML PATH ('')
        ), 2, 1000) [idstable]
From dbo.idstable ST2

2 个答案:

答案 0 :(得分:1)

语法错误的原因是DISTINCT之后的无关列名。以下是使用STUFFTYPE来避免字符串中特殊字符出现问题的类似方法。

SELECT DISTINCT
    STUFF(
        (
            SELECT ','+CAST(ST1.id AS varchar(10)) AS [text()]
            FROM dbo.idstable ST1
            WHERE ST1.id = ST2.id
            ORDER BY ST1.id
            FOR XML PATH (''), TYPE
        ).value('.', 'nvarchar(MAX)'), 1, 1, '') [Students]
FROM dbo.idstable ST2;

旧SQL版本上聚合字符串连接的另一种受支持方法是游标。

答案 1 :(得分:1)

Dan的答案是正确的,就此而言。从性能角度来看,最好在子查询中执行distinct(并且可能在外部查询中包含id

SELECT id
       STUFF( (SELECT ',' + CAST(ST1.id AS varchar(10)) AS [text()]
               FROM dbo.idstable ST1
               WHERE ST1.id = ST2.id
               ORDER BY ST1.id
               FOR XML PATH (''), TYPE
              ).value('.', 'nvarchar(MAX)'
                     ), 1, 1, '') as [Students]
FROM (SELECT DISTINCT id dbo.idstable) ST2;