As The Question says that I'm Trying to insert some values from dynamic sql Query to TempTable using Pivot, so the ExistingCoulmnName
are not known to me
In the next step I want to perform some arithmatic operation lets say multipliation on those Column Values.
How Can I do that?
Attaching Some samples :
select @cols = STUFF((SELECT ',' + QUOTENAME(FYYear)
from #TempCapEx
group by FYYear
order by FYYear
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT CapitalExpenditureId,' + @cols + ' into
##GlobalTempForCapExPivotResult from
(
select CapitalExpenditureId, FYYear, indicatorvalue
from #TempCapEx
) x
pivot
(
sum(indicatorvalue)
for FYYear in (' + @cols + ')
) p'
execute (@query ) ;
So I have a ##GlobalTempForCapExPivotResult
as :
CapitalExpenditureId 2016-2017 2017-2018 2018-2019 2019-2020 2020-2021 2021-2022 2022-2023
22150 0.0000 35200.0000 35200.0000 35200.0000 35200.0000 35200.0000 NULL
32632 NULL 213695.0000 224379.0000 235599.0000 247379.0000 259748.0000 0.0000
1589 10252.0000 170370.0000 0.0000 0.0000 0.0000 0.0000 NULL
14988 0.0000 133000.0000 0.0000 0.0000 0.0000 0.0000 NULL
36877 NULL 303.0300 404.040 101.010 0.0000 0.0000 0.0000
So the Financial Year Columns may increase or decrease, so how can I do somthing like this :
Select [ExistingCoulmnName] * 3.5 from #GlobalTempForCapExPivotResult where [ExistingCoulmnName] = '[2016-2017]'
Expected Output:
CapitalExpenditureId 2016-2017 2017-2018 2018-2019 2019-2020 2020-2021 2021-2022 2022-2023
22150 0.00 * 3.5 35200.0000 * 3.5 35200.0000 * 3.5 35200.0000 * 3.5 35200.0000 * 3.5 35200.0000 * 3.5 NULL * 3.5
There is no native way to do that inside a standard SQL statement. Instead you use some language (possibly even T-SQL) to write a new query in to a string, and then execute that new query. Much the same as your example already does.
Also, note that this type of problem is WHY you shouldn't make that global temporary table in the first place. Normalised data structures are much friendlier to SQL. Do the formatting outside of SQL.
This is your query without the global temporary table...
You as a human being might prefer the flat file (excel style) table, but it is a really bad idea to make that type of table for use inside SQL. Stick to normalised data structures, and learn how to use them. Don't try to break SQL.
You need to create a dynamic UPDATE statement:
that updates the global temp table.