尝试为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用于返回第一个非null值,但我读过它可以用来逗号分隔返回的值表。
答案 0 :(得分: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('')”,您会说“将所有返回的行连接起来并将其与空字符串连接在一起作为周围标记”。虽然这可以让你到达你需要去的地方,但是如果你传递一个空字符串之外的其他内容,可以使用它来查看它的行为。