I need to select from a dynamic table name
Posted: Mon Apr 20, 2009 5:43 pm
I am writing a stored procedure where I select a table name from a table. I am being forced to do this because the developer who wrote the app was a retard. Basically there is a table of table names I need to select from, giving myself a @table_name variable. Then I need to use that variable as the table name to select more data from. Something like this:
The problem is, when I do this, it assumes @table_name is a set of data. It expects @table_name to be a recordset. How do I make it use it as a string, so that it selects from the table name contained in @table_name?
Code: Select all
DECLARE @table_name VARCHAR(50);
SELECT table_name
FROM my_tables
WHERE id = 4;
SELECT *
FROM @table_name
WHERE 1 = 1;