17

我正在使用通用系统进行报告,该系统从数据库视图(SQL Server 2005)中获取数据。在此视图中,我必须将一对多关系中的数据合并到一行中,并使用priyanka.sarkar在此线程中描述的解决方案:将子查询中的多个结果组合成一个逗号分隔值。该解决方案使用 SQLXML 合并数据(子查询):

SELECT STUFF(
    (    SELECT ', ' + Name 
         FROM MyTable _in 
         WHERE _in.ID = _out.ID 
         FOR XML PATH('')),        -- Output multiple rows as one xml type value,
                                   -- without xml tags
    1, 2, '')      -- STUFF: Replace the comma at the beginning with empty string
FROM MyTable _out 
GROUP BY ID        -- Removes duplicates

除了我的数据现在通过 SQLXML 获得 XML 编码(& => 等)之外,它工作得很好(它甚至没有那么重)  & - 毕竟我不想要 XML 数据,我只是把它用作一个技巧 - 并且因为通用系统我无法围绕它进行编码来清理它,因此编码数据直接进入报告。我不能在通用系统中使用存储过程,因此这里不能选择 CURSOR-merging 或 COALESCE-ing ...

所以我正在寻找的是 T-SQL 中的一种方式,它可以让我再次解码 XML,甚至更好:避免 SQLXML 对其进行编码。显然我可以编写一个存储函数来执行此操作,但我更喜欢内置的、更安全的方式......

谢谢你的帮助...

4

2 回答 2

22
(
select ...
from t
for xml path(''), type
).value('.', 'nvarchar(max)')
于 2012-01-13T20:26:14.767 回答
5

如果指定type为选项for xml,则可以使用 XPath 查询将 XML 类型转换回varchar. 使用示例表变量:

declare @MyTable table (id int, name varchar(50))

insert @MyTable (id, name) select 1, 'Joel & Jeff'
union all select 1, '<<BIN LADEN>>'
union all select 2, '&&BUSH&&'

一种可能的解决方案是:

select  b.txt.query('root').value('.', 'varchar(max)')
from    (
        select  distinct id
        from    @MyTable
        ) a
cross apply
        (
            select  CASE ROW_NUMBER() OVER(ORDER BY id) WHEN 1 THEN '' 
                        ELSE ', ' END + name
        from    @MyTable
        where   id = a.id
        order by 
                id
        for xml path(''), root('root'), type
        ) b(txt)

这将打印:

Joel & Jeff, <<BIN LADEN>>
&&BUSH&&

这是没有 XML 转换的替代方法。它确实有一个递归查询,因此性能里程可能会有所不同。来自Quassnoi 的博客

;WITH   with_stats(id, name, rn, cnt) AS
        (
        SELECT  id, name,
                ROW_NUMBER() OVER (PARTITION BY id ORDER BY name),
                COUNT(*) OVER (PARTITION BY id)
        FROM    @MyTable
        ),
        with_concat (id, name, gc, rn, cnt) AS
        (
        SELECT  id, name,
                CAST(name AS VARCHAR(MAX)), rn, cnt
        FROM    with_stats
        WHERE   rn = 1
        UNION ALL
        SELECT  with_stats.id, with_stats.name,
                CAST(with_concat.gc + ', ' + with_stats.name AS VARCHAR(MAX)),
                with_stats.rn, with_stats.cnt
        FROM    with_concat
        JOIN    with_stats
        ON      with_stats.id = with_concat.id
                AND with_stats.rn = with_concat.rn + 1
        )
SELECT  id, gc
FROM    with_concat
WHERE   rn = cnt
OPTION  (MAXRECURSION 0)
于 2010-07-08T10:32:09.580 回答