Drop multiple databases with names matching a pattern

后端 未结 10 2109
南旧
南旧 2021-02-02 10:39

I want to drop all the databases starting with a word.

abc
xyz
cms_db1
cms_db2
cms_xyz
pqr

In the example given above, I will like to drop all

10条回答
  •  一向
    一向 (楼主)
    2021-02-02 11:09

    Improvising on the excellent answer by @cloakedninjas, for easier retrieval of all the queries to execute in a single string.

    Firstly, you can set the maximum value for group_concat_max_len to the maximum possible value, for this particular session:

    SET SESSION group_concat_max_len = @@max_allowed_packet;
    

    Now, you can prepare a query string (to execute later) using SQL. Using information_schema, we can get name of all the databases matching the pattern. Now, use Concat() to prepare a single DROP DATABASE .. query, and then utilize Group_Concat() to merge them all into a single string, for easier retrieval.

    SELECT GROUP_CONCAT(CONCAT('DROP DATABASE `', SCHEMA_NAME, '`;') 
                        SEPARATOR ' ') AS query_to_execute
    FROM information_schema.SCHEMATA
    WHERE SCHEMA_NAME LIKE 'cms_%'
    

    Now copy the string in query_to_execute and run it separately.

提交回复
热议问题