Is there a way to create an array of tables (or dynamical created tables) based on a dynamic value? For example I know that in C++ you can use pointers and dynamic memory but i need to do something like this in SQL.
A user specifies they want to see X years of data for each year we need see 15+ columns that can be built into a temp table (identical for each year).
user selects 5
years worth of data and current year as 2018
, so I will want to create dynamically a local table for 2018, 2017, 2016, 2015 and 2014.
Each table will track customer data, sales etc. Same for each table.
if the above is not possible could we limit the user to only pick the year and dynamically always stick to 5 years for example. User specifies they want to start with 2017
and we will by default build for them 2017, 2016 ... 2013.
i can go ahead and say create table #year1, #year2, #year3 etc.
But that requires a lot of coding (mostly copying and pasting in advance). Is there a way to avoid this -- to say create table #years[]
or a pointer? and then dynamically build some kind of array of #years table.
What we will end up doing is going through the exact same query/logic pulling the exact same data sets year by year. Then at the end comparing who/falls into which year and how. Bottom line is to avoid copying and pasting the same declare/select/insert statements 5 or more times? (and if at all possible to avoid cursors/loops)
I tried coding something like this
DECLARE @season_counter int = 5
DECLARE @cnt int = 0
Declare @cnt_v varchar(1) = CONVERT(varchar(10), @cnt)
DECLARE @SQL NVARCHAR(max) = ''
WHILE @cnt <= @season_counter
BEGIN
select @SQL = @SQL + ' create table #year' + @cnt_v
+ ' (customer_no int, order_no int, perf_no int, due_amt money, paid_amt money, status int ) '
exec sp_executesql @SQL
print @SQL
set @cnt = @cnt + 1
set @cnt_v = CONVERT(varchar(10), @cnt)
set @sql = ''
END
select * from #year1
select * from #year2
The above generated errors
Msg 208, Level 16, State 0, Line 81
Invalid object name '#year1'.
I cant use global variables and i sure as hell don't want to declare Create statements for 20 tables (as some max value). I want it to be dynamic and on the fly. Please advise.