Ramco Ramco

Ramco Ramco

  • 442
  • 3.4k
  • 528.7k

Insert Pivot Data into Temp Table at runtime

May 26 2022 9:03 AM

Hi

 I have below code and i want to insert Pivot Data into another temp table created at runtime.

CREATE TABLE #temp(Location int,
Quantity numeric(19,6),itemName nvarchar(50))

insert into #temp
select cast(T1.Loc as int) 'Location',
IsNull(sum(T0.Qty),0) 'Quantity', Concat(T2.ItemCode, ' ' ,T2.ItemName) 'Item Description'
From SLS1 T0
inner join SMaster T1 on T0.entry = T1.entry
inner join MItem T2 on T0.ItemCode = T2.ItemCode
where T1.TransDATE = '2022/04/26' 
GROUP BY T1.Loc,T2.ItemName,T2.ItemCode

declare @cols as nvarchar(max)='';
declare @query as nvarchar(max)='';
select @cols = @cols + QUOTENAME(ItemName) + ',' from (Select distinct ItemName from #temp) as tmp
select @cols = substring(@cols,0,len(@cols))
set @query = 'select Location, ' + @cols + ' from (select Location,Quantity,itemname from #temp) x pivot
( Sum(quantity) for itemname in (' + @cols + ')) piv ';
execute (@query)
Loc Product 1 Product 2
1 NULL NULL
2 30 NULL

Product 1 , Product 2 are dynamic . There can be Product 3 , Product 4 and so on.

Thanks


Answers (4)