I had to built a dynamic PIVOT in SQL Server as described in this article using the following script:
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(Course)
FROM (SELECT DISTINCT Course FROM #CourseSales) AS Courses
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT Year, ' + @ColumnName + '
FROM #CourseSales
PIVOT(SUM(Earning)
FOR Course IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
It works great and it returns a dynamic table as expected.
However, I would like to be able to select it in an other query but can not find a proper way to do so:
- A view does not work as it does not accept variables
- A table valued function does not work as I don't know in advance the structure of the output table
- A stored procedure does not work as I can not use it in a SELECT query
What would be the best solution to save this dynamic pivot query and be able to SELECT it afterwards?
Thank you
Sylvain