0

I am trying to access a table through its name, which is of varchar data type. The name of the table is stored in a field on another table and I want to be able to get that. For example, say the table name is stored in varchar variable @tablename;

SELECT * FROM @tablename

general syntax isn't working - is there any way to do this?

Raj
  • 10,653
  • 2
  • 45
  • 52
Ryan Hargreaves
  • 267
  • 3
  • 16

1 Answers1

0

You will need to use dynamic sql to do this

DECLARE @SQL varchar(max)
SET @SQL = 'SELECT * FROM '+@tablename

EXEC(@SQL)
Raj
  • 10,653
  • 2
  • 45
  • 52