A table name as a variable

I am trying to execute this query:

declare @tablename varchar(50)
set @tablename="test"
select * from @tablename

This produces the following error:

Msg 1087, Level 16, State 1, Line 5

Must declare the table variable “@tablename”.

What’s the right way to have the table name populated dynamically?

10 Answers
10

Leave a Comment