sql - Select from table with dynamic compute name -
i want write query in name table dynamicaly compute. have code below. should put in 'magic code' region?
declare @mytablename nvarchar(100) = 'sch' + cast(@nowyear varchar(5)) + 'q' + cast(@nowquarter varchar(3)) + '.[tvisits]' -- magic code -- mytable = dosomething(@akttablename) -- magic code -- select * mytable
i use ms sql server 2012
you need use dynamic sql -
declare @nowyear int = 2013 , @nowquarter int = 1 declare @mytablename nvarchar(100) = '[sch' + cast(@nowyear varchar(5)) + 'q' + cast(@nowquarter varchar(3)) + '].[tvisits]' declare @sql nvarchar(max) = n'select * ' + @mytablename exec sys.sp_executesql @sql