Question

I want to change this query:

CREATE TABLE diablo.diablo_sales2 LIKE diablo.diablo_sales;

to a dynamic one like this:

set @old = 'diablo_sales';
set @new = 'diablo_sales2 ';
set @schema = 'diablo';

set @query = 'create table @schema.@new like @schema.@old';

Is this even possible in MySQL? How can I execute @query?

EDIT: below is the whole query I'm trying to make dynamic

 -- create same table structure - blank table
CREATE TABLE diablo.diablo_sales2 LIKE diablo.diablo_sales;

-- add the new column(s)
ALTER TABLE diablo.diablo_sales2 
add column new_column decimal(10);


-- insert the old data into new table - new column will remain blank
INSERT INTO diablo.diablo_sales2 
(
column1,
column2

)
SELECT * FROM diablo.diablo_sales;

-- rename the new table to its original name. Drop the old table.
RENAME table diablo_sales TO `old`, diablo_sales2 TO diablo_sales;
DROP TABLE old;
Was it helpful?

Solution

You can use the SQL Syntax for Prepared Statements:

SET @sql := CONCAT('
  CREATE TABLE `',REPLACE(@schema,'`','``'),'`.`',REPLACE(@new,'`','``'),'`
          LIKE `',REPLACE(@schema,'`','``'),'`.`',REPLACE(@old,'`','``'),'`
');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

I have taken the liberty of quoting the identifiers and calling REPLACE() to escape any quotes contained therein, in order to protect against SQL injection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top