Renaming Mysql Multiple Template Tables

I know how to run

RENAME TABLE onetable_test TO onetable;

But is there a way to rename many tables with a template and not write a lot of code, for example

RENAME TABLE onetable_test TO onetable;
RENAME TABLE twotable_test TO twitable;
RENAME TABLE threetable_test TO threetable;    
...

I am using mysql.

Thanks!

0
source share
3 answers

Use the stored procedure below:

DELIMITER $$

CREATE

PROCEDURE `Rename_Tables`()

BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE tableName VARCHAR(50);
DECLARE newTableName VARCHAR(70);
DECLARE t_query VARCHAR(500);
DECLARE cur1 CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_name LIKE '%table_test' AND table_schema='test' ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN cur1;

read_loop: LOOP
    FETCH cur1 INTO tableName;
    IF done THEN
        LEAVE read_loop;
    END IF;
    SET newTableName = SUBSTRING(tableName, 1,LOCATE('_',tableName)-1);
    SET t_query = CONCAT('RENAME TABLE ', tableName, ' TO ', newTableName);

    SET @myQuery = t_query;
    PREPARE stmt FROM @myQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END LOOP;

END$$

DELIMITER;

Replace table_schema with your name table_schema.

+3
source

For example:

select group_concat(v.name SEPARATOR ' ') 
from (
      select concat('rename table ', t.table_name, ' to ', substring(reverse(v.name), instr(reverse(v.name), '_') + 1, length(v.name)) name 
      from information_schema.tables t
      where 
          table_schema = 'put_your_table_schema'
          and table_name like '%_test'
     ) v;
  • Running this query will return a script that must be executed to rename the tables.
  • substring(reverse.....), and not just replace(v.name, '_test', ''), because we need to be sure that we will only replace tags _testonly at the end of the line.

Hope this helps

0
source

@ravnur:

SET group_concat_max_len=5000;
SELECT group_concat(v.name separator '; ')
FROM (
    SELECT concat('RENAME TABLE ', t.table_name, ' TO ', replace(t.table_name, 'wp_', 'blog_')) name
    FROM information_schema.tables t
    WHERE table_name like 'wp_%'
) v;

Useful if you want to rename your Wordpress tables from the default prefix from wp_to blog_(for example). Copy and paste the output of this command into the mysql or phpMyAdmin shell.

0
source

All Articles