Search code examples
mysqlstringstored-procedurescreate-table

MySQL create table name from string


I want to create a table name in MySQL but use a string value I've declared. Is this possible? I'm thinking of something like this:

DECLARE new_table_name VARCHAR(255);
SET new_table_name = CONCAT("foo",123);
CREATE TABLE new_table_name (
    ...etc...
)

So far, I can't figure out how to do this. Btw I've got this in a stored procedure.


Solution

  • Use the following code in your stored procedure:

    BEGIN
    
    DECLARE new_table_name VARCHAR(255);
    SET new_table_name = CONCAT("foo",123);
    
    SET @createTable = CONCAT("CREATE TABLE ", new_table_name, "(id int, some_col varchar(55))");
    
    PREPARE createStmt FROM @createTable;
    EXECUTE createStmt;
    DEALLOCATE PREPARE createStmt;
    
    END$$