I have to write a dynamic pivot based on a complex query and I want to use a common table expression to create the dataset on which I have to build the pivot to keep it outside the dynamic sql and have it compiled
My problem is that I don't know if i can use the CTE in a SET where I wrap the dynamic SQL I have to execute.
let see the code:
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
This way i get an error near SET @DynamicPivotQuery =
If I replace SET with a SELECT the stored procedure is compiled but if i run it I get:
Invalid object name 'DatiCTE'