Dynamic table name in MySQL
Posted: December 31, 2010 | Author: Gautam Kumar | Filed under: How-To |Leave a commentHOW-TO Create a Table with a dynamic name generated at runtime
DECLARE id_val INT(11) ; DECLARE table_lnk VARCHAR(255) ;- #Some arbitratry sql
SELECT `<column>` INTO id_val FROM `<table>` WHERE `<condition>`; #Create the new table name SET @create_query = ‘CREATE TABLE `?` (<column/s> )’; SET table_lnk=CONCAT(id_val,‘_table’); SET @create_query =REPLACE(@create_query,‘?’,table_lnk); #Prepare the create table statement # preparation is necessary for dynamic table name prepare create_table_stmt FROM @create_query; execute create_table_stmt ; DEALLOCATE PREPARE create_table_stmt;
What the above code does is, it gets a value from a table and based on the value it creates a table with that name ,
to do this we use the replace function to replace the `?` with the required table name .
Since we cannot directly execute a sql statement stored in a variable we need to prepare it and then execute .
But make sure to deallocate it immidiately after execution