4

This query runs, but it produces the name of a table as a result, rather than actually selecting from that table.

SELECT T.* 
  FROM (SELECT tablename 
          FROM ListOfTables 
         WHERE id = 0) AS T

where ListOfTables contains id=0, tablename='some_table', I want to return the same result set as if I had written this directly:

SELECT * FROM some_table

Is there a native way to do this in MySQL 5, or do I have to do in in the application?

spraff
  • 32,570
  • 22
  • 121
  • 229

3 Answers3

5

To do this in MySQL, you need to create a prepared statement which you can only create from a user variable:

SELECT @tn := tablename FROM ListOfTables WHERE id = 0;

SET @qs = CONCAT('SELECT * FROM ', @tn);
PREPARE ps FROM @qs;
EXECUTE ps;
AndreKR
  • 32,613
  • 18
  • 106
  • 168
  • What about where `id` is a parameter? – spraff Feb 26 '12 at 16:35
  • I don't understand. Of course you can feed in the id value from your application like usual. You can even make the first query a prepared statement, too. – AndreKR Feb 26 '12 at 16:36
  • I need to make it all a single statement for PHP's `mysql_query` -- I'm playing around with it but can't find a way to fold everything together without a parse error. – spraff Feb 26 '12 at 16:41
  • This is because, to cite http://php.net/manual/en/function.mysql-query.php, multiple queries are not supported. You have to use a different client API, make a stored procedure or find another solution, maybe in http://stackoverflow.com/questions/345637/php-multiple-sql-queries-in-one-mysql-query-statement – AndreKR Feb 26 '12 at 16:45
3

You need to use dynamic SQL to get this result (the below code assumes SQL Server, I can't speak for other RDBMS').

declare @tableName varchar(100)
declare @query varchar(500)

select @tableName = tablename
from ListOfTables
where id = 0

select @query = 'select * from ' + @tableName

exec (@query)
0

Almost the same as @Shark's answer, except you also quote the name of the table to avoid syntax errors.

-- Using variables just for better readability.
DECLARE @Name NVARCHAR(4000)
DECLARE @Query NVARCHAR(4000)

-- Get the relevant data
SET @Name = QUOTENAME(SELECT tablename FROM ListOfTables WHERE id=0)
-- Build query 
SET @Query = 'SELECT * FROM ' + @Schema + '.' + @Name + ''
-- execute it.
EXEC(@Query)
Oybek
  • 7,016
  • 5
  • 29
  • 49