Dynamic Pivot Results to a Temp Table
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(QT.QUESTION_DESC)
FROM #QUES_TEMP QT
GROUP BY QT.QUESTION_DESC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT EVAL_ID, AuditType, ' + @cols + '
from
(
select QT.EVAL_ID,
QT.AuditType,
QT.SCORE,
QT.QUESTION_DESC
from #QUES_TEMP QT
) x
pivot
(
max(SCORE)
for QUESTION_DESC in (' + @cols + ')
) p '
set @query = 'select * into ##Temp from ('+@query+') y'
execute(@query)
select * from ##Temp
Source :: https://stackoverflow.com/questions/22503366/dynamic-pivot-results-to-a-temp-table