Home >Database >Mysql Tutorial >How to Execute SQL Queries with Dynamic Table Names in MySQL?
Dynamic Table Names in SQL Statements
Executing SQL queries with dynamic table names can be challenging. Consider the following example:
SET @id := '47'; SET @table := @id+'_2013_2014_voucher'; SELECT * FROM @table; Delete FROM @table where>
This query throws the following error:
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@table' at line 1
Solution Using Prepared Statements
The recommended approach for handling dynamic table names is to use prepared statements. Prepared statements allow you to dynamically specify the table name while ensuring proper syntax and security. In MySQL, you can use the PREPARE and EXECUTE statements as follows:
SET @id := '47'; SET @table := concat(@id,'_2013_2014_voucher'); set @qry1:= concat('select * from ',@table); prepare stmt from @qry1 ; execute stmt ;
The CONCAT() function is used to dynamically concatenate the table name string. The prepared statement is then executed, avoiding the syntax error.
Applying to Delete Query
The same approach can be extended to delete queries:
SET @qry2:= concat('DELETE FROM ',@table,' where>
The above is the detailed content of How to Execute SQL Queries with Dynamic Table Names in MySQL?. For more information, please follow other related articles on the PHP Chinese website!