How to rename all tables in a MySQL database

12

I have a MySQL database with several tables and I'm migrating to another database.

  

I have a Client and must be a client PE

     

I have Product and must be Product_PE

How can I accomplish this without however pausing to rename each of the 50 tables?

    
asked by anonymous 26.03.2015 / 04:52

3 answers

11

The easiest way , since 50 is a not-so-large number of rows:

RENAME TABLE
    Cliente TO Cliente_PE,
    Produto TO Produto_PE,
    TabelaX TO TabelaX_PE

See the SQL manual .

You can also do this using phpmyadmin , but then you'll be adding a prefix to the tables (PE_Client, etc):

  • Select the database that contains the tables in the side menu.
  • Check the Check All checkbox.
  • No select next to select Add prefix to table .
  • In the "Add prefix" field type prefix_ , in your case, PE_ .
  •     
    26.03.2015 / 05:20
    19

    To rename a table, you use the

    RENAME TABLE nomeOriginal TO nomeNovo
    

    Since there are many tables, you can use this query to automatically generate all% s of% s:

    SELECT
       CONCAT(
          'RENAME TABLE '', table_schema, ''.'', table_name,
          '' TO '', table_schema, ''.'', table_name, '_PE';' )
    FROM
       INFORMATION_SCHEMA.TABLES WHERE table_schema="NomeDoDb";
    

    Output example:

    RENAME TABLE 'NomeDoDb'.'eventos' TO 'NomeDoDb'.'eventos_PE';
    RENAME TABLE 'NomeDoDb'.'fotos' TO 'NomeDoDb'.'fotos_PE';
    RENAME TABLE 'NomeDoDb'.'usuarios' TO 'NomeDoDb'.'usuarios_PE';
    

    Then just take the result and execute as a new query, either via copy & paste , redirecting to a SQL script, etc.

    Advantages:

    • It places a Suffix in the tables, but can be easily adapted for prefixes or mixed;
    • Avoid typing all table names manually;
    • Easy to delete a group of tables by filtering RENAME or manually;
    • Easy to work on more than one DB using the WHERE clause;
    • Does not rely on a specific tool, can be used on command line, or even visual tools such as MySQL workbench.
    • If you need to do this periodically, you can create a WHERE , and use it whenever you need, eg PROCEDURE
    26.03.2015 / 05:28
    0

    In phpmyadmin (or adminer), go to "SQL" and type the command:

    RENAME TABLE current_name TO new_name

    Click Run. After that, give F4 to update the list of bank tables!

        
    12.07.2018 / 00:38