Mohemmad K
Mohemmad K

Reputation: 839

Storing records to temporary table inside dynamic query when using Pivot.

I am new to sql programming.

I want to store the records returned as result set from the pivot query.

Pivot's columns are selected dynamically.

My query is:

declare @cols nvarchar(max)

set @cols=STUFF((select distinct ',[' + LTRIM(rtrim(year(Dt)))+']' from temp FOR XML PATH('')),1,1,'');

EXEC('select * from 
(select YEAR(Dt)[year],Software,Ver from temp)T
Pivot(count([year]) for [year] in ('+@cols+'))PVT')

I want to store this result to the temporary table for further reporting.

Please help me. Thanks in advance.

Upvotes: 0

Views: 1073

Answers (1)

Praveen Nambiar
Praveen Nambiar

Reputation: 4892

Try the below query. You will have to use INTO.

declare @cols nvarchar(max)

set @cols=STUFF((select distinct ',[' + LTRIM(rtrim(year(Dt)))+']' 
from temp 
FOR XML PATH('')),1,1,'');

EXEC('select * INTO ##temptable from 
    (select YEAR(Dt)[year],Software,Ver from temp)T
    Pivot(count([year]) for [year] in ('+@cols+'))PVT')

Upvotes: 1

Related Questions