Search code examples
mysqlcopyproceduredynamic-sql

MySQL Copy table procedure fails


What am i doing wrong with this procedure??

# Copy tabel 
CREATE PROCEDURE `table_backup`(tablename varchar(50))
begin
set @copy_from = tablename;
set @copy_to = CONCAT(tablename, `_`, DATE_FORMAT(NOW(), '%d_%m_%yt%H_%i_%s'));
CREATE TABLE @copy_to LIKE @copy_from;
INSERT @copy_to SELECT * FROM @copy_from;
end

CALL table_backup('table_name');

Solution

  • You will need to perform your query dynamically. This is how you can achieve it in a stored procedure:

    mysql> delimiter //
    mysql> create procedure dynamic_query()
       -> begin
       -> set @query=concat("select *from DemoTable2033 where Id=3");
       -> prepare st from @query;
       -> execute st;
       -> end
       -> //
    Query OK, 0 rows affected (0.13 sec)
    
    mysql> delimiter ;
    

    You will need to perform the create table and insert into as dynamic query. Depending on your settings you might need to perform them as separate dynamic queries, using the same pattern.

    Read more at https://www.tutorialspoint.com/implement-dynamic-sql-query-inside-a-mysql-stored-procedure