我生成了一个 SQL 查询,该查询生成一个 SQL 查询并执行它。
我希望在视图或 Excel 中将此查询提供给不使用 SQL Server Management Studio 的用户。
我发现了几个 描述如何从 Excel 运行存储过程的博客文章。
可悲的是,它们不适合我。
这里是存储过程的查询/SQL:
DECLARE @template nvarchar(1000)
DECLARE @script nvarchar(max)
DECLARE @dbname nvarchar(max)
DECLARE c CURSOR FOR
select name from master.sys.databases
WHERE name LIKE '%REPORTING'
OPEN c
SET @template = 'SELECT
''CUSTOMER_PLACEHOLDER'' AS Customer
,rd.[ReportName]
,min(ri.RenderingStart) AS FirstRequest
,max(ri.RenderingEnd) AS LastRequest
,count(ri.ReportInstanceGUID) AS TimesRendered
FROM [DBNAME_PLACEHOLDER].[dbo].[ReportDefinition] rd
LEFT JOIN DBNAME_PLACEHOLDER.dbo.ReportJob rj ON rj.ReportDefinitionGUID = rd.ReportDefinitionGUID
LEFT JOIN DBNAME_PLACEHOLDER.dbo.ReportInstance ri ON ri.ReportJobGUID = rj.ReportJobGUID
GROUP BY rd.ReportName'
SET @script = ''
FETCH NEXT FROM c INTO @dbname
DECLARE @first bit
SET @first = 1
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @customer nvarchar(6)
SET @customer = SUBSTRING(@dbname,14,6)
IF @first = 1
BEGIN
SET @script = @template
SET @first = 0
END
ELSE
--SET @script = @script+'
--UNION ALL
--'+@template
SET @script = REPLACE(@script,'CUSTOMER_PLACEHOLDER', @customer)
SET @script = REPLACE(@script,'DBNAME_PLACEHOLDER', @dbname)
FETCH NEXT FROM c
INTO @dbname
END
EXEC (@script)
CLOSE c
DEALLOCATE c
该ELSE
部分已被注释以在 Excel 中查看错误。
查询会在这样执行时运行。
在 Excel 中调用它时,出现以下错误(以管理员身份启动 Excel 时已验证同样发生):
我不知道从哪里继续。表值函数也不起作用,因为它们中不允许执行 EXEC。如果可能的话,我想保留动态部分,因为数据库的数量和名称可能会发生变化 - 我想保持它不具体。
提示?