0

尝试为 SQL Reporting Services 数据库的目录表中列出的每个报告获取逗号分隔的参数列表:

WITH cte AS (
    SELECT
    [Path], [Name], CreationDate, ModifiedDate,    
    CAST(parameter AS XML) AS parameter
    FROM     [dbo].[Catalog] AS c
)
SELECT  [Path], [Name], CreationDate, ModifiedDate, COALESCE(p.nodes('./Name')) 
FROM    cte AS c
    LEFT JOIN c.Parameter.nodes('/Parameters/Parameter') AS T ( p )
ORDER BY c.[Path]

在 BOL 中,它说 COALESCE 用于返回第一个非空值,但我读过它可用于逗号分隔返回的值表。

4

1 回答 1

1

我不知道使用 COALESCE 生成 CSV 的任何方法。但是,我确实对 XML PATH 查询使用了标准技巧:

WITH cte AS (
    SELECT  [Path] ,
            [Name] ,
            CreationDate ,
            ModifiedDate ,
            CAST(parameter AS XML) AS parameter
    FROM    [dbo].[Catalog] AS c
), 
cte2 AS (
SELECT  [Path] ,
        p.value('(./Name)[1]', 'nvarchar(50)') AS [Parameter]
FROM    [cte] AS c
CROSS APPLY c.parameter.nodes('/Parameters/Parameter') AS T ( p )
)

SELECT [Path], 
    STUFF((
        SELECT ',' + [Parameter] 
        from cte2 c2
        WHERE c.[Path] = c2.[Path]    
        FOR XML PATH('') 
    ), 1, 1, '')
from [dbo].[Catalog] AS c

本质上,通过在查询末尾抛出“FOR XML PATH('')”,您可以说“获取所有返回的行并将它们与一个空字符串连接在一起作为周围的标记”。虽然这可以让你到达你需要去的地方,但如果你传入一个空字符串之外的东西,你可以试试看它的行为。

于 2012-08-10T21:23:56.850 回答