我正在处理一个SQL Server的查询(目前使用2008 R2) - 我的目标是生成一个结果集,列出在具体路径下定义的SSRS中的每个报告以及一个网格,其中每个唯一命名的报告参数在服务器上都有一列,网格内容对于每个对应报告和参数组合都是“勾选”(例如非空值),这样可以说明相应报告具有相应名称的参数。 查询需要区分大小写报告参数名称 - 查询的一个目的是识别拼写不一致的参数的报告。
我能够使用许多技巧(有些人可能称之为丑陋的黑科技)编写该查询:
我能够使用许多技巧(有些人可能称之为丑陋的黑科技)编写该查询:
use ReportServer
go
declare @path nvarchar(255);
set @path = N'SSRS Path To Folder'
-- return a table with two columns: ReportName, ParameterName with one row for each
-- distinct ReportName + ParameterName combination
select
t.Name as ReportName,
pn.value collate Latin1_General_CS_AI as ParameterName
into
#rp
from
(
-- return a table with two columns: ReportName and ParameterNames (comma-separated list of
-- parameters in declaration order)
select
[Name],
(select STUFF((select ', ' + p.n.value('.', 'varchar(255)')
from ParameterXml.nodes('/Parameters/Parameter/Name') p(n)
for xml path('')), 1, 2, '')
) as ParameterNames
from
(
select
*,
CAST(Parameter as xml) as ParameterXml
from
[Catalog]
) c
where
[Path] like '/' + @path + '/%'
and [Type] = 2
) t
cross apply dbo.SplitString(t.ParameterNames) pn
-- Pivot the above result into a table with one row per report and one column for each
-- distinct report parameter name. Parameter-named columns contain a flag - 1 or null -
-- that indicates whether the report corresponding to that row defines the parameter
-- corresponding to that column.
create database CS_Temp collate Latin1_General_CS_AI;
go
use CS_Temp
go
declare @cols nvarchar(MAX), @query nvarchar(MAX);
set @cols = STUFF(
(
select
distinct ','+QUOTENAME(rp.ParameterName)
from
#rp rp
for xml path(''), type).value('.', 'nvarchar(max)'
),1,1,''
);
set @query = 'SELECT ReportName, ' + @cols + ' from
(
select ReportName, 1 as Used, ParameterName from #rp
) x
pivot
(
max(Used) for ParameterName in (' + @cols + ')
) p
';
execute(@query)
go
drop table #rp
use ReportServer;
go
drop database CS_Temp;
go
< p >(Erland Sommarskog/Itzik Ben-Gan的SplitString函数,Aaron Bertrand的动态轴技术)。这个查询确实有效,但速度较慢且不美观 - 对于我的用例来说实际上是可以接受的。我想知道的是,是否有更好的方法使数据透视表按照大小写敏感的列名工作,而不是我在此处所做的:创建具有区分大小写排序规则的数据库,切换到该上下文并执行数据透视查询。该数据库除了为数据库元数据 - 即数据透视查询结果中的列名提供排序规则外没有任何作用。