The general approach for creating dynamic queries in MySQL stored procedures is correct; construct a string of SQL (using CONCAT as necessary), and then execute that SQL. However, there are a few syntax differences between Microsoft SQL Server and MySQL that come into play.
There is no "TOP" clause in MySQL. Instead, use ORDER BY and LIMIT clauses at the end of the query to return the first few rows from a set:
SELECT * FROM theTable ORDER BY someField LIMIT 5
MySQL offers two types of variables. User variables, prefaced with an '@' symbol, persist beyond the routine. Local variables exist only within the routine. In either case, variable assignments in MySQL stored procedures use the SET or SELECT...INTO statements. Building dynamic queries requires use of a user variable, rather than a local variable, along with the SQL syntax for prepared statements:
SET @statement = CONCAT('SELECT * FROM ', tableNameVariable); PREPARE myStatement FROM @statement; EXECUTE myStatement;Click here for more on stored procedures in MySQL. For more on prepared statements in MySQL, read the manual.
Dig Deeper on Linux servers
Related Q&A from Scott Noyes
A MySQL expert offers a workaround for the lack of syntax support for full outer joins. Continue Reading
The differences between MySQL Enterprise and MySQL Community. Continue Reading
An expert explains how multiple storage engines work within MySQL. Continue Reading