要查询的行数未知且将变量作为输入需要连接到其他表。
我创建了一个StoredPrecodure-FnGetSumScoreHelper(1)返回具有未知行数的表。将1视为sp的输入变量@regionId。 此sp返回要执行的查询,并与其他表联接。
ALTER PROCEDURE [dbo].[SpFnGetSumScoreQuery]
-- Add the parameters for the stored procedure here
@regionId nvarchar(255) ,
@output nvarchar(max) output
AS
BEGIN
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(CategoryId)
from FnGetSumScoreHelper(1)
group by CategoryId
order by CategoryId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @output = 'SELECT PeriodId,' + @cols + ' from
(
select CategoryId, PeriodId, Score
from FnGetSumScoreHelper(1)
) x
pivot
(
sum(Score)
for CategoryId in (' + @cols + ')
) p '
return
这是我想将其连接到其他表的方式:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@SumScoreCategories nvarchar(max)
EXEC SpFnGetSumScoreQuery 1, @SumScoreCategories OUTPUT
select [Period].Id as PeriodId, [period].[Name] as PeriodName,
RegionPeriodScore.AdminScore, RegionPeriodScore.UserScore
from [period] left join RegionPeriodScore on [period].Id = RegionPeriodScore.PeriodId
inner join
(
execute(@SumScoreCategories)
) SumScoreCategories
on RegionPeriodScore.periodid = SumScoreCategories.periodid
我知道我无法加入sp,但是与需要输入变量的动态数据透视表结合的解决方案是什么?因为表值函数无法执行查询。