2

Is it possible in a sequence of SQL statements to get the value of a field and use that to name a table in another statement? I'm not sure if that's clear, so here's an psudo-example of what I'm trying to do:

// dataType is equal to "ratings"
@var = select dataType from theTable where anID = 5;

// needs to run as "from ratings-table"
select field1,field2 from @var-table where anID = 5;

I've been reading http://dev.mysql.com/doc/refman/5.0/en/user-variables.html but either I don't properly understand this, or its not the solution I'm looking for.

1
  • In your example, anID = 5 in both situations for the field1, field2 you would like to get. Is this also true in your database? Commented Jan 25, 2011 at 16:18

1 Answer 1

5

Yes, you can do this using prepared statements:

SET @TableName := 'ratings';
SET @CreateQuery := CONCAT('SELECT `field1`, `field2` FROM `', @TableName, '-table` WHERE `anID` = 5');
PREPARE statementCreate FROM @CreateQuery;
EXECUTE statementCreate;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.