You can use dynamic sql:
DECLARE @SQL varchar(max), @i INT
SET @i=2
while (@i<=22)
begin
/* Then cover all calculations with this one: */
SET @SQL='SELECT [DEF].[CONCATENATE], SUM(DEF.[C1_'+cast(@i as varchar)+'_PREV]) as
[C1_'+cast(@i as varchar)+'_prev]
INTO #TMP_C1_'+cast(@i as varchar)+'_CONCATENATE_PREV
FROM DEF
GROUP BY DEF.[CONCATENATE]
/* and all your code with the same trick in @i to the END */
'
--PRINT (@SQL) -- print it before use to see the result script
EXEC (@SQL)
/* Than do your iterations etc. */
set @i+=1
end
And don't forget to substitute all ' inside @SQL with ''. Also you need to do all manipulations with temp tables inside @SQL, if you want to do final update outside the dynamic sql, just make tables real and then delete them.
[UPDATE] As far as you faced with problem of altering temp tables, I tried to reproduce this error, but nothing happens, everything works fine. Please use this code as an example.
declare @sql varchar(max),@i int
set @i=2
while @i<=22
begin
set @sql='
select ID,Code into #TMP_C1_'+cast(@i as varchar)+'_CONCATENATE_PREV from (select 0 as ID, ''a'' as Code) t1
alter table #TMP_C1_'+cast(@i as varchar)+'_CONCATENATE_PREV add [Col1] varchar(255), [Col2] Varchar(255), [Col3] Money
select * from #TMP_C1_'+cast(@i as varchar)+'_CONCATENATE_PREV'
--print (@sql)
exec (@sql)
set @i+=1
end
First, I create temp table with dynamic name. Second, add new columns. The last is successful verifying. Did you execute all creations/alters in the same @sql-batch? If no, this won't work, because this tables are available only inside this batch (that's why we used varchar(max) when declared). Please describe your actions in details, maybe there is a mistake somewhere.