I'm writing a select statement to make a table name a variable whose value is set according to a condition:
tablename := emp table
select * from tablename;
But I get an error message. How do I make this statement work?
Your syntax is close to what you need. But you need to call the EXECUTE command with the SQL string. Here's code you can run in Query Analyzer that uses a variable for the table name and retrieves all the records from the Employees table:
DECLARE @TableName varchar(255)
SET @TableName = 'Employees'
EXEC ('SELECT * FROM ' + @TableName)