我必须根据复杂的查询编写动态数据透视图,我想使用公用表表达式创建数据集,我必须在其上构建数据集以使其保持在动态sql之外并将其编译为
我的问题是,我不知道我是否可以在SET中使用CTE,我将执行动态SQL包装。
让我们看看代码:
WITH DatiCTE AS
(
SELECT ...
)
SET @DynamicPivotQuery =
N'SELECT IdActivity, ' + @PivotSelectColumnNames + '
FROM DatiCTE
PIVOT(SUM(NumOfDays)
FOR Area IN (' + @PivotColumnNames + ')) AS PVTTable'
WHERE 1 = 1
EXEC sp_executesql @DynamicPivotQuery
这样我就会在SET @DynamicPivotQuery =
如果我用SELECT替换SET,则编译存储过程,但是如果我运行它,我得到:
Invalid object name 'DatiCTE'
答案 0 :(得分:1)
将CTE WITH DatiCTE AS
的定义移动到动态sql中,如下所示:
SET @DynamicPivotQuery =
N'WITH DatiCTE AS
(
SELECT ...
)
SELECT IdActivity, ' + @PivotSelectColumnNames + '
FROM DatiCTE
PIVOT(SUM(NumOfDays)
FOR Area IN (' + @PivotColumnNames + ')) AS PVTTable'
+ 'WHERE 1 = 1';
EXEC sp_executesql @DynamicPivotQuery;
答案 1 :(得分:0)
现在我切换到临时表:
SELECT ...
INTO @TempTable
SET @DynamicPivotQuery =
N'
SELECT IdActivity, ' + @PivotSelectColumnNames + '
FROM @TempTable
PIVOT(SUM(NumOfDays)
FOR Area IN (' + @PivotColumnNames + ')) AS PVTTable'
+ 'WHERE 1 = 1';
EXEC sp_executesql @DynamicPivotQuery;
但我对并发用户有疑问。我尝试表变量,但不能用于动态SQL ...