问题
I know how to run
RENAME TABLE onetable_test TO onetable;
But is there a method to rename many tables with a pattern and don't write a lot of code like
RENAME TABLE onetable_test TO onetable;
RENAME TABLE twotable_test TO twitable;
RENAME TABLE threetable_test TO threetable;
...
I am using mysql.
Thanks!
回答1:
Use below stored procedure ::
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 table_schema name.
回答2:
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 script that should be executed to rename tables.
substring(reverse.....)
rather than simplereplace(v.name, '_test', '')
used because we need to be sure that we will replace only_test
occurrences only at the end of the string.
Hope it helps
回答3:
A slight modification on @ravnur's answer:
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 when you want to rename your Wordpress tables from the default prefix of wp_
to blog_
(for example). Copy and paste the output of that command into the mysql shell or phpMyAdmin.
回答4:
I wanted to update what worked for me since this post is pretty old. I needed to add the ` mark before and after the table names. And don't forget to add the last ; because this can sometimes throw a syntax error.
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_', 'wplocal_'), '`') name
FROM information_schema.tables t
WHERE table_name like 'wp_%'
) v;
来源:https://stackoverflow.com/questions/11642020/mysql-rename-multiple-tables-with-a-pattern