Table name as parameter sql
-
Maybe who will answer that challenge:
There are tables in the database that have names
table15
♪table14
♪ ♪ ♪table00
♪ It is necessary to write a stored procedure which, as a parameter, should receive the year by which the table for the execution of requests should be determined.Dynamic SQL doesn't use it because it's a big code! Is there any solution for this task?
-
All tables (table15...) should be combined in one view with the addition of a unique identifier (in this case, the last two digits of the year) as an additional column. When requested in the procedure, join the yearly and unique identifier. Thus, only a certain table will be taken from the view.
Simplified example:
declare @t1 table (id int) declare @t2 table (id int)
insert into @t1 values(1)
insert into @t1 values(2)
insert into @t1 values(3)insert into @t2 values(4)
insert into @t2 values(5)
insert into @t2 values(6)select * from
(select 1 as Id, * from @t1
union all
select 2, * from @t2) t
where Id = 1