A
A
Alexander2015-12-17 11:28:21
MySQL
Alexander, 2015-12-17 11:28:21

How to use variable as table name in SELECT?

There is a need to generate a table name depending on the current time, it is formed like this:
"SELECT CONCAT('dbname.tableprefix',DATE_FORMAT(NOW(),'%Y%m')) INTO @tablename;"
Next, you need to execute the query "SELECT `somefield` FROM @tablename;"
MySQL (5.5.44) throws a syntax error.
How to use variable value as table name for query?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2015-12-17
@zzzmmtt

Found a solution.
SELECT CONCAT('dbname.tableprefix',DATE_FORMAT(NOW(),'%Y%m')) into @t;
SET @sqltext=concat('select `somefield` from ',@t);
PREPARE sel FROM @sqltext;
EXECUTE sel;
DEALLOCATE PREPARE sel;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question