Magic Lasso
Magic Lasso

Reputation: 1542

Use result as table name for select statement in mssql

Any way to use the result of a query as the table name for a select statement. I was trying the below query @tblname is jsut the resultset not the string result that i need:

declare @tblname varchar(50)
declare @sql nvarchar(1000)
declare @stand  varchar(20)
set @stand = 'test'
set @sql = 'select @temp=atbl.table_name from test_products wap inner join attribute_tables atbl on (atbl.id = wap.colors_tbl_id) where wap.dept = @stand'
execute sp_executesql @sql, N'@stand nvarchar(20),@temp nvarchar(50) OUTPUT', @stand=@stand, @temp = @tblname OUTPUT
declare @test nvarchar(30)
set @test = @tblname
set @sql = 'SELECT * FROM @tblname'
execute(@sql)

Upvotes: 1

Views: 2122

Answers (1)

Oded
Oded

Reputation: 498924

You need to concatenate the SQL string:

...
set @sql = 'SELECT * FROM ' + @tblname
execute(@sql)

Table names, as well as column names cannot be parameterized.

Upvotes: 2

Related Questions